🪢 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
feat(api): support v2 SDKs (#644) (#656)
Max Deichmann45f091eeeeb3
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.ymlindex eaec1eeeb3..953e6ca988 100644--- a/fern/apis/server/definition/commons.yml+++ b/fern/apis/server/definition/commons.yml@@ -1,32 +1,4 @@types:- # Create Bodies- CreateEventRequest:- properties:- id: optional<string>- traceId: optional<string>- name: optional<string>- startTime: optional<datetime>- metadata: optional<unknown>- input: optional<unknown>- output: optional<unknown>- level: optional<ObservationLevel>- statusMessage: optional<string>- parentObservationId: optional<string>- version: optional<string>- CreateSpanRequest:- extends: CreateEventRequest- properties:- endTime: optional<datetime>- CreateGenerationRequest:- extends: CreateSpanRequest- properties:- completionStartTime: optional<datetime>- model: optional<string>- modelParameters: optional<map<string, MapValue>>- prompt: optional<unknown>- completion: optional<unknown>- usage: optional<LLMUsage>-# ObjectsTrace:properties:@@ -83,12 +55,16 @@ types:version: optional<string>metadata: optional<unknown>output: optional<unknown>- promptTokens: integer- completionTokens: integer- totalTokens: integer+ usage: optional<Usage>level: ObservationLevelstatusMessage: optional<string>parentObservationId: optional<string>+ Usage:+ properties:+ input: optional<integer>+ output: optional<integer>+ total: optional<integer>+ unit: optional<ModelUsageUnit>Score:properties:id: string@@ -136,6 +112,10 @@ types:datasetRunItems: list<DatasetRunItem># Utilities+ ModelUsageUnit:+ enum:+ - CHARACTERS+ - TOKENSObservationLevel:enum:- DEBUG@@ -148,11 +128,6 @@ types:- optional<string>- optional<integer>- optional<boolean>- LLMUsage:- properties:- promptTokens: optional<integer>- completionTokens: optional<integer>- totalTokens: optional<integer>DatasetStatus:enum:- ACTIVEdiff --git a/fern/apis/server/definition/event.yml b/fern/apis/server/definition/event.ymldeleted file mode 100644index 7ef16cefc0..0000000000--- a/fern/apis/server/definition/event.yml+++ /dev/null@@ -1,13 +0,0 @@-# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json-imports:- commons: ./commons.yml-service:- auth: true- base-path: /api/public- endpoints:- create:- docs: Add an event to the database- method: POST- path: /events- request: commons.CreateEventRequest- response: commons.Observationdiff --git a/fern/apis/server/definition/generations.yml b/fern/apis/server/definition/generations.ymldeleted file mode 100644index c06044a1f5..0000000000--- a/fern/apis/server/definition/generations.yml+++ /dev/null@@ -1,37 +0,0 @@-# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json-imports:- commons: ./commons.yml- pagination: ./utils/pagination.yml-service:- auth: true- base-path: /api/public- endpoints:- log:- method: POST- path: /generations- request: commons.CreateGenerationRequest- response: commons.Observation- update:- method: PATCH- path: /generations- request: UpdateGenerationRequest- response: commons.Observation--types:- UpdateGenerationRequest:- properties:- generationId: string- traceId: optional<string>- name: optional<string>- startTime: optional<datetime>- endTime: optional<datetime>- completionStartTime: optional<datetime>- model: optional<string>- modelParameters: optional<map<string, commons.MapValue>>- prompt: optional<unknown>- version: optional<string>- metadata: optional<unknown>- completion: optional<unknown>- usage: optional<commons.LLMUsage>- level: optional<commons.ObservationLevel>- statusMessage: optional<string>diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.ymlindex f3b81913a0..160d168915 100644--- a/fern/apis/server/definition/ingestion.yml+++ b/fern/apis/server/definition/ingestion.yml@@ -15,7 +15,7 @@ service:body:properties:batch: list<IngestionEvent>- response: commons.Score+ response: IngestionResponse # will be reportet as 200 response, but endpoint returns 207types:IngestionEvent:@@ -23,26 +23,194 @@ types:union:trace-create: TraceEventscore-create: ScoreEvent- observation-create: ObservationCreateEvent- observation-update: ObservationUpdateEvent+ event-create: CreateEventEvent+ generation-create: CreateGenerationEvent+ generation-update: UpdateGenerationEvent+ span-create: CreateSpanEvent+ span-update: UpdateSpanEvent++ # both are legacy+ observation-create: CreateObservationEvent+ observation-update: UpdateObservationEvent++ ObservationType:+ enum:+ - SPAN+ - GENERATION+ - EVENT++ IngestionUsage:+ discriminated: false+ union:+ - commons.Usage+ - OpenAIUsage++ OpenAIUsage:+ properties:+ promptTokens: optional<integer>+ completionTokens: optional<integer>+ totalTokens: optional<integer>++ OptionalObservationBody:+ properties:+ traceId: optional<string>+ name: optional<string>+ startTime: optional<datetime>+ metadata: optional<unknown>+ input: optional<unknown>+ output: optional<unknown>+ level: optional<commons.ObservationLevel>+ statusMessage: optional<string>+ parentObservationId: optional<string>+ version: optional<string>++ CreateEventBody:+ extends: OptionalObservationBody+ properties:+ id: optional<string>++ UpdateEventBody:+ extends: OptionalObservationBody+ properties:+ id: string++ CreateSpanBody:+ extends: CreateEventBody+ properties:+ endTime: optional<datetime>++ UpdateSpanBody:+ extends: UpdateEventBody+ properties:+ endTime: optional<datetime>++ CreateGenerationBody:+ extends: CreateSpanBody+ properties:+ completionStartTime: optional<datetime>+ model: optional<string>+ modelParameters: optional<map<string, commons.MapValue>>+ usage: optional<IngestionUsage>++ UpdateGenerationBody:+ extends: UpdateSpanBody+ properties:+ completionStartTime: optional<datetime>+ model: optional<string>+ modelParameters: optional<map<string, commons.MapValue>>+ usage: optional<IngestionUsage>++ ObservationBody:+ properties:+ id: optional<string>+ traceId: optional<string>+ type: ObservationType+ name: optional<string>+ startTime: optional<datetime>+ endTime: optional<datetime>+ completionStartTime: optional<datetime>+ model: optional<string>+ modelParameters: optional<map<string, commons.MapValue>>+ input: optional<unknown>+ version: optional<string>+ metadata: optional<unknown>+ output: optional<unknown>+ usage: optional<commons.Usage>+ level: optional<commons.ObservationLevel>+ statusMessage: optional<string>+ parentObservationId: optional<string>++ TraceBody:+ properties:+ id: optional<string>+ name: optional<string>+ userId: optional<string>+ input: optional<unknown>+ output: optional<unknown>+ sessionId: optional<string>+ release: optional<string>+ version: optional<string>+ metadata: optional<unknown>+ public:+ type: optional<boolean>+ docs: Make trace publicly accessible via url++ ScoreBody:+ properties:+ id: optional<string>+ traceId: string+ name: string+ value: double+ observationId: optional<string>+ comment: optional<string>TraceEvent:properties:id: stringtimestamp: string- body: commons.Trace- ObservationCreateEvent:+ body: TraceBody++ CreateObservationEvent:properties:id: stringtimestamp: string- body: commons.Observation- ObservationUpdateEvent:+ body: ObservationBody++ UpdateObservationEvent:properties:id: stringtimestamp: string- body: commons.Observation+ body: ObservationBody+ScoreEvent:properties:id: stringtimestamp: string- body: commons.Score+ body: ScoreBody++ CreateGenerationEvent:+ properties:+ id: string+ timestamp: string+ body: CreateGenerationBody++ UpdateGenerationEvent:+ properties:+ id: string+ timestamp: string+ body: UpdateGenerationBody++ CreateSpanEvent:+ properties:+ id: string+ timestamp: string+ body: CreateSpanBody++ UpdateSpanEvent:+ properties:+ id: string+ timestamp: string+ body: UpdateSpanBody++ CreateEventEvent:+ properties:+ id: string+ timestamp: string+ body: CreateEventBody++ IngestionSuccess:+ properties:+ id: string+ status: integer++ IngestionError:+ properties:+ id: string+ status: integer+ message: optional<string>+ error: optional<unknown>++ IngestionResponse:+ properties:+ successes: list<IngestionSuccess>+ errors: list<IngestionError>diff --git a/fern/apis/server/definition/span.yml b/fern/apis/server/definition/span.ymldeleted file mode 100644index d8781d8366..0000000000--- a/fern/apis/server/definition/span.yml+++ /dev/null@@ -1,34 +0,0 @@-# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json-imports:- commons: ./commons.yml-service:- auth: true- base-path: /api/public- endpoints:- create:- docs: Add a span to the database- method: POST- path: /spans- request: commons.CreateSpanRequest- response: commons.Observation- update:- docs: Update a span to the database- method: PATCH- path: /spans- request: UpdateSpanRequest- response: commons.Observation--types:- UpdateSpanRequest:- properties:- spanId: string- traceId: optional<string>- startTime: optional<datetime>- endTime: optional<datetime>- name: optional<string>- metadata: optional<unknown>- input: optional<unknown>- output: optional<unknown>- level: optional<commons.ObservationLevel>- version: optional<string>- statusMessage: optional<string>diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.ymlindex 6973289880..2e0f577862 100644--- a/fern/apis/server/definition/trace.yml+++ b/fern/apis/server/definition/trace.yml@@ -6,12 +6,6 @@ service:auth: truebase-path: /api/publicendpoints:- create:- docs: Add a trace to the database- method: POST- path: /traces- request: CreateTraceRequest- response: commons.Traceget:docs: Get a specific tracemethod: GET@@ -35,21 +29,6 @@ service:response: Tracestypes:- CreateTraceRequest:- properties:- id: optional<string>- name: optional<string>- userId: optional<string>- externalId: optional<string>- input: optional<unknown>- output: optional<unknown>- sessionId: optional<string>- release: optional<string>- version: optional<string>- metadata: optional<unknown>- public:- type: optional<boolean>- docs: Make trace publicly accessible via urlTraces:properties:data: list<commons.TraceWithDetails>diff --git a/fern/fern.config.json b/fern/fern.config.jsonindex cf97c4489a..09bbcff5ff 100644--- a/fern/fern.config.json+++ b/fern/fern.config.json@@ -1,4 +1,4 @@{"organization": "finto",- "version": "0.16.3"+ "version": "0.16.7"}\ No newline at end of filediff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.ymlindex 7ba79de35e..772c6ba824 100644--- a/generated/openapi-server/openapi.yml+++ b/generated/openapi-server/openapi.yml@@ -282,141 +282,6 @@ paths:application/json:schema: {}security: *ref_0- /api/public/events:- post:- description: Add an event to the database- operationId: event_create- tags:- - Event- parameters: []- responses:- '200':- description: ''- content:- application/json:- schema:- $ref: '#/components/schemas/Observation'- '400':- description: ''- content:- application/json:- schema: {}- '401':- description: ''- content:- application/json:- schema: {}- '403':- description: ''- content:- application/json:- schema: {}- '404':- description: ''- content:- application/json:- schema: {}- '405':- description: ''- content:- application/json:- schema: {}- security: *ref_0- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/CreateEventRequest'- /api/public/generations:- post:- operationId: generations_log- tags:- - Generations- parameters: []- responses:- '200':- description: ''- content:- application/json:- schema:- $ref: '#/components/schemas/Observation'- '400':- description: ''- content:- application/json:- schema: {}- '401':- description: ''- content:- application/json:- schema: {}- '403':- description: ''- content:- application/json:- schema: {}- '404':- description: ''- content:- application/json:- schema: {}- '405':- description: ''- content:- application/json:- schema: {}- security: *ref_0- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/CreateGenerationRequest'- patch:- operationId: generations_update- tags:- - Generations- parameters: []- responses:- '200':- description: ''- content:- application/json:- schema:- $ref: '#/components/schemas/Observation'- '400':- description: ''- content:- application/json:- schema: {}- '401':- description: ''- content:- application/json:- schema: {}- '403':- description: ''- content:- application/json:- schema: {}- '404':- description: ''- content:- application/json:- schema: {}- '405':- description: ''- content:- application/json:- schema: {}- security: *ref_0- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/UpdateGenerationRequest'/api/public/health:get:description: Check health of API and database@@ -467,7 +332,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/Score'+ $ref: '#/components/schemas/IngestionResponse''400':description: ''content:@@ -831,111 +696,26 @@ paths:application/json:schema: {}security: *ref_0- /api/public/spans:- post:- description: Add a span to the database- operationId: span_create- tags:- - Span- parameters: []- responses:- '200':- description: ''- content:- application/json:- schema:- $ref: '#/components/schemas/Observation'- '400':- description: ''- content:- application/json:- schema: {}- '401':- description: ''- content:- application/json:- schema: {}- '403':- description: ''- content:- application/json:- schema: {}- '404':- description: ''- content:- application/json:- schema: {}- '405':- description: ''- content:- application/json:- schema: {}- security: *ref_0- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/CreateSpanRequest'- patch:- description: Update a span to the database- operationId: span_update- tags:- - Span- parameters: []- responses:- '200':- description: ''- content:- application/json:- schema:- $ref: '#/components/schemas/Observation'- '400':- description: ''- content:- application/json:- schema: {}- '401':- description: ''- content:- application/json:- schema: {}- '403':- description: ''- content:- application/json:- schema: {}- '404':- description: ''- content:- application/json:- schema: {}- '405':- description: ''- content:- application/json:- schema: {}- security: *ref_0- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/UpdateSpanRequest'- /api/public/traces:- post:- description: Add a trace to the database- operationId: trace_create+ /api/public/traces/{traceId}:+ get:+ description: Get a specific trace+ operationId: trace_gettags:- Trace- parameters: []+ parameters:+ - name: traceId+ in: path+ description: The unique langfuse identifier of a trace+ required: true+ schema:+ type: stringresponses:'200':description: ''content:application/json:schema:- $ref: '#/components/schemas/Trace'+ $ref: '#/components/schemas/TraceWithFullDetails''400':description: ''content:@@ -962,12 +742,7 @@ paths:application/json:schema: {}security: *ref_0- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/CreateTraceRequest'+ /api/public/traces:get:description: Get list of tracesoperationId: trace_list@@ -1031,124 +806,8 @@ paths:application/json:schema: {}security: *ref_0- /api/public/traces/{traceId}:- get:- description: Get a specific trace- operationId: trace_get- tags:- - Trace- parameters:- - name: traceId- in: path- description: The unique langfuse identifier of a trace- required: true- schema:- type: string- responses:- '200':- description: ''- content:- application/json:- schema:- $ref: '#/components/schemas/TraceWithFullDetails'- '400':- description: ''- content:- application/json:- schema: {}- '401':- description: ''- content:- application/json:- schema: {}- '403':- description: ''- content:- application/json:- schema: {}- '404':- description: ''- content:- application/json:- schema: {}- '405':- description: ''- content:- application/json:- schema: {}- security: *ref_0components:schemas:- CreateEventRequest:- title: CreateEventRequest- type: object- properties:- id:- type: string- nullable: true- traceId:- type: string- nullable: true- name:- type: string- nullable: true- startTime:- type: string- format: date-time- nullable: true- metadata:- nullable: true- input:- nullable: true- output:- nullable: true- level:- $ref: '#/components/schemas/ObservationLevel'- nullable: true- statusMessage:- type: string- nullable: true- parentObservationId:- type: string- nullable: true- version:- type: string- nullable: true- CreateSpanRequest:- title: CreateSpanRequest- type: object- properties:- endTime:- type: string- format: date-time- nullable: true- allOf:- - $ref: '#/components/schemas/CreateEventRequest'- CreateGenerationRequest:- title: CreateGenerationRequest- type: object- properties:- completionStartTime:- type: string- format: date-time- nullable: true- model:- type: string- nullable: true- modelParameters:- type: object- additionalProperties:- $ref: '#/components/schemas/MapValue'- nullable: true- prompt:- nullable: true- completion:- nullable: true- usage:- $ref: '#/components/schemas/LLMUsage'- nullable: true- allOf:- - $ref: '#/components/schemas/CreateSpanRequest'Trace:title: Tracetype: object@@ -1292,12 +951,9 @@ components:nullable: trueoutput:nullable: true- promptTokens:- type: integer- completionTokens:- type: integer- totalTokens:- type: integer+ usage:+ $ref: '#/components/schemas/Usage'+ nullable: truelevel:$ref: '#/components/schemas/ObservationLevel'statusMessage:@@ -1310,10 +966,23 @@ components:- id- type- startTime- - promptTokens- - completionTokens- - totalTokens- level+ Usage:+ title: Usage+ type: object+ properties:+ input:+ type: integer+ nullable: true+ output:+ type: integer+ nullable: true+ total:+ type: integer+ nullable: true+ unit:+ $ref: '#/components/schemas/ModelUsageUnit'+ nullable: trueScore:title: Scoretype: object@@ -1458,6 +1127,12 @@ components:- createdAt- updatedAt- datasetRunItems+ ModelUsageUnit:+ title: ModelUsageUnit+ type: string+ enum:+ - CHARACTERS+ - TOKENSObservationLevel:title: ObservationLeveltype: string@@ -1475,19 +1150,6 @@ components:nullable: true- type: booleannullable: true- LLMUsage:- title: LLMUsage- type: object- properties:- promptTokens:- type: integer- nullable: true- completionTokens:- type: integer- nullable: true- totalTokens:- type: integer- nullable: trueDatasetStatus:title: DatasetStatustype: string@@ -1531,58 +1193,6 @@ components:type: stringrequired:- name- UpdateGenerationRequest:- title: UpdateGenerationRequest- type: object- properties:- generationId:- type: string- traceId:- type: string- nullable: true- name:- type: string- nullable: true- startTime:- type: string- format: date-time- nullable: true- endTime:- type: string- format: date-time- nullable: true- completionStartTime:- type: string- format: date-time- nullable: true- model:- type: string- nullable: true- modelParameters:- type: object- additionalProperties:- $ref: '#/components/schemas/MapValue'- nullable: true- prompt:- nullable: true- version:- type: string- nullable: true- metadata:- nullable: true- completion:- nullable: true- usage:- $ref: '#/components/schemas/LLMUsage'- nullable: true- level:- $ref: '#/components/schemas/ObservationLevel'- nullable: true- statusMessage:- type: string- nullable: true- required:- - generationIdIngestionEvent:title: IngestionEventoneOf:@@ -1608,6 +1218,61 @@ components:- $ref: '#/components/schemas/ScoreEvent'required:- type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - event-create+ - $ref: '#/components/schemas/CreateEventEvent'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - generation-create+ - $ref: '#/components/schemas/CreateGenerationEvent'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - generation-update+ - $ref: '#/components/schemas/UpdateGenerationEvent'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - span-create+ - $ref: '#/components/schemas/CreateSpanEvent'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - span-update+ - $ref: '#/components/schemas/UpdateSpanEvent'+ required:+ - type- type: objectallOf:- type: object@@ -1616,7 +1281,7 @@ components:type: stringenum:- observation-create- - $ref: '#/components/schemas/ObservationCreateEvent'+ - $ref: '#/components/schemas/CreateObservationEvent'required:- type- type: object@@ -1627,47 +1292,299 @@ components:type: stringenum:- observation-update- - $ref: '#/components/schemas/ObservationUpdateEvent'+ - $ref: '#/components/schemas/UpdateObservationEvent'required:- type- TraceEvent:- title: TraceEvent+ ObservationType:+ title: ObservationType+ type: string+ enum:+ - SPAN+ - GENERATION+ - EVENT+ IngestionUsage:+ title: IngestionUsage+ oneOf:+ - $ref: '#/components/schemas/Usage'+ - $ref: '#/components/schemas/OpenAIUsage'+ OpenAIUsage:+ title: OpenAIUsagetype: objectproperties:- id:+ promptTokens:+ type: integer+ nullable: true+ completionTokens:+ type: integer+ nullable: true+ totalTokens:+ type: integer+ nullable: true+ OptionalObservationBody:+ title: OptionalObservationBody+ type: object+ properties:+ traceId:type: string- timestamp:+ nullable: true+ name:type: string- body:- $ref: '#/components/schemas/Trace'- required:- - id- - timestamp- - body- ObservationCreateEvent:- title: ObservationCreateEvent+ nullable: true+ startTime:+ type: string+ format: date-time+ nullable: true+ metadata:+ nullable: true+ input:+ nullable: true+ output:+ nullable: true+ level:+ $ref: '#/components/schemas/ObservationLevel'+ nullable: true+ statusMessage:+ type: string+ nullable: true+ parentObservationId:+ type: string+ nullable: true+ version:+ type: string+ nullable: true+ CreateEventBody:+ title: CreateEventBodytype: objectproperties:id:type: string- timestamp:+ nullable: true+ allOf:+ - $ref: '#/components/schemas/OptionalObservationBody'+ UpdateEventBody:+ title: UpdateEventBody+ type: object+ properties:+ id:type: string- body:- $ref: '#/components/schemas/Observation'required:- id- - timestamp- - body- ObservationUpdateEvent:- title: ObservationUpdateEvent+ allOf:+ - $ref: '#/components/schemas/OptionalObservationBody'+ CreateSpanBody:+ title: CreateSpanBodytype: objectproperties:- id:+ endTime:+ type: string+ format: date-time+ nullable: true+ allOf:+ - $ref: '#/components/schemas/CreateEventBody'+ UpdateSpanBody:+ title: UpdateSpanBody+ type: object+ properties:+ endTime:+ type: string+ format: date-time+ nullable: true+ allOf:+ - $ref: '#/components/schemas/UpdateEventBody'+ CreateGenerationBody:+ title: CreateGenerationBody+ type: object+ properties:+ completionStartTime:+ type: string+ format: date-time+ nullable: true+ model:+ type: string+ nullable: true+ modelParameters:+ type: object+ additionalProperties:+ $ref: '#/components/schemas/MapValue'+ nullable: true+ usage:+ $ref: '#/components/schemas/IngestionUsage'+ nullable: true+ allOf:+ - $ref: '#/components/schemas/CreateSpanBody'+ UpdateGenerationBody:+ title: UpdateGenerationBody+ type: object+ properties:+ completionStartTime:+ type: string+ format: date-time+ nullable: true+ model:+ type: string+ nullable: true+ modelParameters:+ type: object+ additionalProperties:+ $ref: '#/components/schemas/MapValue'+ nullable: true+ usage:+ $ref: '#/components/schemas/IngestionUsage'+ nullable: true+ allOf:+ - $ref: '#/components/schemas/UpdateSpanBody'+ ObservationBody:+ title: ObservationBody+ type: object+ properties:+ id:+ type: string+ nullable: true+ traceId:+ type: string+ nullable: true+ type:+ $ref: '#/components/schemas/ObservationType'+ name:+ type: string+ nullable: true+ startTime:+ type: string+ format: date-time+ nullable: true+ endTime:+ type: string+ format: date-time+ nullable: true+ completionStartTime:+ type: string+ format: date-time+ nullable: true+ model:+ type: string+ nullable: true+ modelParameters:+ type: object+ additionalProperties:+ $ref: '#/components/schemas/MapValue'+ nullable: true+ input:+ nullable: true+ version:+ type: string+ nullable: true+ metadata:+ nullable: true+ output:+ nullable: true+ usage:+ $ref: '#/components/schemas/Usage'+ nullable: true+ level:+ $ref: '#/components/schemas/ObservationLevel'+ nullable: true+ statusMessage:+ type: string+ nullable: true+ parentObservationId:+ type: string+ nullable: true+ required:+ - type+ TraceBody:+ title: TraceBody+ type: object+ properties:+ id:+ type: string+ nullable: true+ name:+ type: string+ nullable: true+ userId:+ type: string+ nullable: true+ input:+ nullable: true+ output:+ nullable: true+ sessionId:+ type: string+ nullable: true+ release:+ type: string+ nullable: true+ version:+ type: string+ nullable: true+ metadata:+ nullable: true+ public:+ type: boolean+ nullable: true+ description: Make trace publicly accessible via url+ ScoreBody:+ title: ScoreBody+ type: object+ properties:+ id:+ type: string+ nullable: true+ traceId:+ type: string+ name:+ type: string+ value:+ type: number+ format: double+ observationId:+ type: string+ nullable: true+ comment:+ type: string+ nullable: true+ required:+ - traceId+ - name+ - value+ TraceEvent:+ title: TraceEvent+ type: object+ properties:+ id:type: stringtimestamp:type: stringbody:- $ref: '#/components/schemas/Observation'+ $ref: '#/components/schemas/TraceBody'+ required:+ - id+ - timestamp+ - body+ CreateObservationEvent:+ title: CreateObservationEvent+ type: object+ properties:+ id:+ type: string+ timestamp:+ type: string+ body:+ $ref: '#/components/schemas/ObservationBody'+ required:+ - id+ - timestamp+ - body+ UpdateObservationEvent:+ title: UpdateObservationEvent+ type: object+ properties:+ id:+ type: string+ timestamp:+ type: string+ body:+ $ref: '#/components/schemas/ObservationBody'required:- id- timestamp@@ -1681,11 +1598,123 @@ components:timestamp:type: stringbody:- $ref: '#/components/schemas/Score'+ $ref: '#/components/schemas/ScoreBody'+ required:+ - id+ - timestamp+ - body+ CreateGenerationEvent:+ title: CreateGenerationEvent+ type: object+ properties:+ id:+ type: string+ timestamp:+ type: string+ body:+ $ref: '#/components/schemas/CreateGenerationBody'+ required:+ - id+ - timestamp+ - body+ UpdateGenerationEvent:+ title: UpdateGenerationEvent+ type: object+ properties:+ id:+ type: string+ timestamp:+ type: string+ body:+ $ref: '#/components/schemas/UpdateGenerationBody'+ required:+ - id+ - timestamp+ - body+ CreateSpanEvent:+ title: CreateSpanEvent+ type: object+ properties:+ id:+ type: string+ timestamp:+ type: string+ body:+ $ref: '#/components/schemas/CreateSpanBody'required:- id- timestamp- body+ UpdateSpanEvent:+ title: UpdateSpanEvent+ type: object+ properties:+ id:+ type: string+ timestamp:+ type: string+ body:+ $ref: '#/components/schemas/UpdateSpanBody'+ required:+ - id+ - timestamp+ - body+ CreateEventEvent:+ title: CreateEventEvent+ type: object+ properties:+ id:+ type: string+ timestamp:+ type: string+ body:+ $ref: '#/components/schemas/CreateEventBody'+ required:+ - id+ - timestamp+ - body+ IngestionSuccess:+ title: IngestionSuccess+ type: object+ properties:+ id:+ type: string+ status:+ type: integer+ required:+ - id+ - status+ IngestionError:+ title: IngestionError+ type: object+ properties:+ id:+ type: string+ status:+ type: integer+ message:+ type: string+ nullable: true+ error:+ nullable: true+ required:+ - id+ - status+ IngestionResponse:+ title: IngestionResponse+ type: object+ properties:+ successes:+ type: array+ items:+ $ref: '#/components/schemas/IngestionSuccess'+ errors:+ type: array+ items:+ $ref: '#/components/schemas/IngestionError'+ required:+ - successes+ - errorsObservations:title: Observationstype: object@@ -1757,78 +1786,6 @@ components:required:- data- meta- UpdateSpanRequest:- title: UpdateSpanRequest- type: object- properties:- spanId:- type: string- traceId:- type: string- nullable: true- startTime:- type: string- format: date-time- nullable: true- endTime:- type: string- format: date-time- nullable: true- name:- type: string- nullable: true- metadata:- nullable: true- input:- nullable: true- output:- nullable: true- level:- $ref: '#/components/schemas/ObservationLevel'- nullable: true- version:- type: string- nullable: true- statusMessage:- type: string- nullable: true- required:- - spanId- CreateTraceRequest:- title: CreateTraceRequest- type: object- properties:- id:- type: string- nullable: true- name:- type: string- nullable: true- userId:- type: string- nullable: true- externalId:- type: string- nullable: true- input:- nullable: true- output:- nullable: true- sessionId:- type: string- nullable: true- release:- type: string- nullable: true- version:- type: string- nullable: true- metadata:- nullable: true- public:- type: boolean- nullable: true- description: Make trace publicly accessible via urlTraces:title: Tracestype: objectdiff --git a/generated/postman/collection.json b/generated/postman/collection.jsonindex 3ab17dc4d0..3d6d61f0e0 100644--- a/generated/postman/collection.json+++ b/generated/postman/collection.json@@ -260,119 +260,6 @@}]},- {- "_type": "container",- "description": null,- "name": "Event",- "item": [- {- "_type": "endpoint",- "name": "Create",- "request": {- "description": "Add an event to the database",- "url": {- "raw": "{{baseUrl}}/api/public/events",- "host": [- "{{baseUrl}}"- ],- "path": [- "api",- "public",- "events"- ],- "query": [],- "variable": []- },- "header": [],- "method": "POST",- "auth": null,- "body": {- "mode": "raw",- "raw": "{\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\",\n \"parentObservationId\": \"example\",\n \"version\": \"example\"\n}",- "options": {- "raw": {- "language": "json"- }- }- }- },- "response": []- }- ]- },- {- "_type": "container",- "description": null,- "name": "Generations",- "item": [- {- "_type": "endpoint",- "name": "Log",- "request": {- "description": null,- "url": {- "raw": "{{baseUrl}}/api/public/generations",- "host": [- "{{baseUrl}}"- ],- "path": [- "api",- "public",- "generations"- ],- "query": [],- "variable": []- },- "header": [],- "method": "POST",- "auth": null,- "body": {- "mode": "raw",- "raw": "{\n \"completionStartTime\": \"1994-11-05T13:15:30Z\",\n \"model\": \"example\",\n \"modelParameters\": {\n \"example\": \"example\"\n },\n \"prompt\": \"UNKNOWN\",\n \"completion\": \"UNKNOWN\",\n \"usage\": {\n \"promptTokens\": 0,\n \"completionTokens\": 0,\n \"totalTokens\": 0\n },\n \"endTime\": \"1994-11-05T13:15:30Z\",\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\",\n \"parentObservationId\": \"example\",\n \"version\": \"example\"\n}",- "options": {- "raw": {- "language": "json"- }- }- }- },- "response": []- },- {- "_type": "endpoint",- "name": "Update",- "request": {- "description": null,- "url": {- "raw": "{{baseUrl}}/api/public/generations",- "host": [- "{{baseUrl}}"- ],- "path": [- "api",- "public",- "generations"- ],- "query": [],- "variable": []- },- "header": [],- "method": "PATCH",- "auth": null,- "body": {- "mode": "raw",- "raw": "{\n \"generationId\": \"example\",\n \"traceId\": \"example\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"endTime\": \"1994-11-05T13:15:30Z\",\n \"completionStartTime\": \"1994-11-05T13:15:30Z\",\n \"model\": \"example\",\n \"modelParameters\": {\n \"example\": \"example\"\n },\n \"prompt\": \"UNKNOWN\",\n \"version\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"completion\": \"UNKNOWN\",\n \"usage\": {\n \"promptTokens\": 0,\n \"completionTokens\": 0,\n \"totalTokens\": 0\n },\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\"\n}",- "options": {- "raw": {- "language": "json"- }- }- }- },- "response": []- }- ]- },{"_type": "container","description": null,@@ -433,7 +320,7 @@"auth": null,"body": {"mode": "raw",- "raw": "{\n \"batch\": [\n {\n \"type\": \"trace-create\",\n \"id\": \"example\",\n \"timestamp\": \"example\",\n \"body\": {\n \"id\": \"example\",\n \"timestamp\": \"1994-11-05T13:15:30Z\",\n \"name\": \"example\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"sessionId\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"userId\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"public\": true\n }\n }\n ]\n}",+ "raw": "{\n \"batch\": [\n {\n \"type\": \"trace-create\",\n \"id\": \"example\",\n \"timestamp\": \"example\",\n \"body\": {\n \"id\": \"example\",\n \"name\": \"example\",\n \"userId\": \"example\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"sessionId\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"public\": true\n }\n }\n ]\n}","options": {"raw": {"language": "json"@@ -702,117 +589,11 @@}]},- {- "_type": "container",- "description": null,- "name": "Span",- "item": [- {- "_type": "endpoint",- "name": "Create",- "request": {- "description": "Add a span to the database",- "url": {- "raw": "{{baseUrl}}/api/public/spans",- "host": [- "{{baseUrl}}"- ],- "path": [- "api",- "public",- "spans"- ],- "query": [],- "variable": []- },- "header": [],- "method": "POST",- "auth": null,- "body": {- "mode": "raw",- "raw": "{\n \"endTime\": \"1994-11-05T13:15:30Z\",\n \"id\": \"example\",\n \"traceId\": \"example\",\n \"name\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"statusMessage\": \"example\",\n \"parentObservationId\": \"example\",\n \"version\": \"example\"\n}",- "options": {- "raw": {- "language": "json"- }- }- }- },- "response": []- },- {- "_type": "endpoint",- "name": "Update",- "request": {- "description": "Update a span to the database",- "url": {- "raw": "{{baseUrl}}/api/public/spans",- "host": [- "{{baseUrl}}"- ],- "path": [- "api",- "public",- "spans"- ],- "query": [],- "variable": []- },- "header": [],- "method": "PATCH",- "auth": null,- "body": {- "mode": "raw",- "raw": "{\n \"spanId\": \"example\",\n \"traceId\": \"example\",\n \"startTime\": \"1994-11-05T13:15:30Z\",\n \"endTime\": \"1994-11-05T13:15:30Z\",\n \"name\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"level\": \"DEBUG\",\n \"version\": \"example\",\n \"statusMessage\": \"example\"\n}",- "options": {- "raw": {- "language": "json"- }- }- }- },- "response": []- }- ]- },{"_type": "container","description": null,"name": "Trace","item": [- {- "_type": "endpoint",- "name": "Create",- "request": {- "description": "Add a trace to the database",- "url": {- "raw": "{{baseUrl}}/api/public/traces",- "host": [- "{{baseUrl}}"- ],- "path": [- "api",- "public",- "traces"- ],- "query": [],- "variable": []- },- "header": [],- "method": "POST",- "auth": null,- "body": {- "mode": "raw",- "raw": "{\n \"id\": \"example\",\n \"name\": \"example\",\n \"userId\": \"example\",\n \"externalId\": \"example\",\n \"input\": \"UNKNOWN\",\n \"output\": \"UNKNOWN\",\n \"sessionId\": \"example\",\n \"release\": \"example\",\n \"version\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"public\": true\n}",- "options": {- "raw": {- "language": "json"- }- }- }- },- "response": []- },{"_type": "endpoint","name": "Get",diff --git a/prisma/migrations/20231204223505_add_unit_to_observations/migration.sql b/prisma/migrations/20231204223505_add_unit_to_observations/migration.sqlnew file mode 100644index 0000000000..eef16391ce--- /dev/null+++ b/prisma/migrations/20231204223505_add_unit_to_observations/migration.sql@@ -0,0 +1,4 @@+-- AlterTable+-- Adding this migration does not lock the postgres table. For non volaitile data, the default value is stored in the+-- table metadata and accessed on read query time. No table re-write is required (https://www.postgresql.org/docs/current/sql-altertable.html#:~:text=When%20a%20column%20is%20added,is%20specified%2C%20NULL%20is%20used.)+ALTER TABLE "observations" ADD COLUMN "unit" TEXT NOT NULL DEFAULT 'TOKENS';\ No newline at end of filediff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 561a35bcdd..2fe0def4de 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -218,6 +218,7 @@ model Observation {promptTokens Int @default(0) @map("prompt_tokens")completionTokens Int @default(0) @map("completion_tokens")totalTokens Int @default(0) @map("total_tokens")+ unit String @default("TOKENS")completionStartTime DateTime? @map("completion_start_time")scores Score[]project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)diff --git a/src/__tests__/generations.servertest.ts b/src/__tests__/generations.servertest.tsindex 809c0f08d2..038a7ceb3d 100644--- a/src/__tests__/generations.servertest.ts+++ b/src/__tests__/generations.servertest.ts@@ -8,67 +8,132 @@ describe("/api/public/generations API Endpoint", () => {beforeEach(async () => await pruneDatabase());afterEach(async () => await pruneDatabase());- it("should create generation after trace", async () => {- await pruneDatabase();-- const traceId = uuidv4();-- await makeAPICall("POST", "/api/public/traces", {- id: traceId,- name: "trace-name",- userId: "user-1",- projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",- });-- const dbTrace = await prisma.trace.findMany({- where: {- id: traceId,+ [+ {+ usage: {+ input: 100,+ output: 200,+ total: 100,+ unit: "CHARACTERS",},- });-- expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.id).toBe(traceId);-- const generationId = uuidv4();- const createGeneration = await makeAPICall(- "POST",- "/api/public/generations",- {- id: generationId,- traceId: traceId,- name: "generation-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- model: "model-name",- modelParameters: { key: "value" },- prompt: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",+ expectedUnit: "CHARACTERS",+ expectedPromptTokens: 100,+ expectedCompletionTokens: 200,+ expectedTotalTokens: 100,+ },+ {+ usage: {+ total: 100,+ unit: "CHARACTERS",},- );-- expect(createGeneration.status).toBe(200);- const dbGeneration = await prisma.observation.findUnique({- where: {- id: generationId,+ expectedUnit: "CHARACTERS",+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ expectedTotalTokens: 100,+ },+ {+ usage: {+ total: 100,},+ expectedUnit: "TOKENS",+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ expectedTotalTokens: 100,+ },+ {+ usage: {+ promptTokens: 100,+ completionTokens: 200,+ totalTokens: 100,+ },+ expectedPromptTokens: 100,+ expectedCompletionTokens: 200,+ expectedTotalTokens: 100,+ expectedUnit: "TOKENS",+ },+ {+ usage: {+ totalTokens: 100,+ },+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ expectedTotalTokens: 100,+ expectedUnit: "TOKENS",+ },+ ].forEach((testConfig) => {+ it(`should create generation after trace 1 ${JSON.stringify(+ testConfig,+ )}`, async () => {+ await pruneDatabase();++ const traceId = uuidv4();++ await makeAPICall("POST", "/api/public/traces", {+ id: traceId,+ name: "trace-name",+ userId: "user-1",+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ release: "1.0.0",+ version: "2.0.0",+ });++ const dbTrace = await prisma.trace.findMany({+ where: {+ id: traceId,+ },+ });++ expect(dbTrace.length).toBeGreaterThan(0);+ expect(dbTrace[0]?.id).toBe(traceId);++ const generationId = uuidv4();+ const createGeneration = await makeAPICall(+ "POST",+ "/api/public/generations",+ {+ id: generationId,+ traceId: traceId,+ name: "generation-name",+ startTime: "2021-01-01T00:00:00.000Z",+ endTime: "2021-01-01T00:00:00.000Z",+ model: "model-name",+ modelParameters: { key: "value" },+ prompt: { key: "value" },+ metadata: { key: "value" },+ version: "2.0.0",+ usage: testConfig.usage,+ },+ );++ expect(createGeneration.status).toBe(200);+ const dbGeneration = await prisma.observation.findUnique({+ where: {+ id: generationId,+ },+ });++ expect(dbGeneration?.id).toBe(generationId);+ expect(dbGeneration?.traceId).toBe(traceId);+ expect(dbGeneration?.name).toBe("generation-name");+ expect(dbGeneration?.startTime).toEqual(+ new Date("2021-01-01T00:00:00.000Z"),+ );+ expect(dbGeneration?.endTime).toEqual(+ new Date("2021-01-01T00:00:00.000Z"),+ );+ expect(dbGeneration?.model).toBe("model-name");+ expect(dbGeneration?.modelParameters).toEqual({ key: "value" });+ expect(dbGeneration?.input).toEqual({ key: "value" });+ expect(dbGeneration?.metadata).toEqual({ key: "value" });+ expect(dbGeneration?.version).toBe("2.0.0");+ expect(dbGeneration?.unit).toBe(testConfig.expectedUnit);+ expect(dbGeneration?.promptTokens).toBe(testConfig.expectedPromptTokens);+ expect(dbGeneration?.completionTokens).toBe(+ testConfig.expectedCompletionTokens,+ );+ expect(dbGeneration?.totalTokens).toBe(testConfig.expectedTotalTokens);});-- expect(dbGeneration?.id).toBe(generationId);- expect(dbGeneration?.traceId).toBe(traceId);- expect(dbGeneration?.name).toBe("generation-name");- expect(dbGeneration?.startTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbGeneration?.model).toBe("model-name");- expect(dbGeneration?.modelParameters).toEqual({ key: "value" });- expect(dbGeneration?.input).toEqual({ key: "value" });- expect(dbGeneration?.metadata).toEqual({ key: "value" });- expect(dbGeneration?.version).toBe("2.0.0");});it("should create generation before trace", async () => {diff --git a/src/__tests__/ingestion.servertest.ts b/src/__tests__/ingestion.servertest.tsindex d0b7d9f0b8..c9932c7f29 100644--- a/src/__tests__/ingestion.servertest.ts+++ b/src/__tests__/ingestion.servertest.ts@@ -8,10 +8,224 @@ import { v4 } from "uuid";describe("/api/public/ingestion API Endpoint", () => {beforeEach(async () => await pruneDatabase());- it("should create trace and generation", async () => {+ [+ {+ usage: {+ input: 100,+ output: 200,+ total: 100,+ unit: "CHARACTERS",+ },+ expectedUnit: "CHARACTERS",+ expectedPromptTokens: 100,+ expectedCompletionTokens: 200,+ expectedTotalTokens: 100,+ },+ {+ usage: {+ total: 100,+ unit: "CHARACTERS",+ },+ expectedUnit: "CHARACTERS",+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ expectedTotalTokens: 100,+ },+ {+ usage: {+ total: 100,+ },+ expectedUnit: "TOKENS",+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ expectedTotalTokens: 100,+ },+ {+ usage: {+ promptTokens: 100,+ completionTokens: 200,+ totalTokens: 100,+ },+ expectedPromptTokens: 100,+ expectedCompletionTokens: 200,+ expectedTotalTokens: 100,+ expectedUnit: "TOKENS",+ },+ {+ usage: {+ totalTokens: 100,+ },+ expectedPromptTokens: 0,+ expectedCompletionTokens: 0,+ expectedTotalTokens: 100,+ expectedUnit: "TOKENS",+ },+ ].forEach((testConfig) => {+ it(`should create trace and generation ${JSON.stringify(+ testConfig,+ )}`, async () => {+ const traceId = v4();+ const generationId = v4();+ const spanId = v4();+ const scoreId = v4();++ const response = await makeAPICall("POST", "/api/public/ingestion", {+ batch: [+ {+ id: v4(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ id: traceId,+ name: "trace-name",+ userId: "user-1",+ metadata: { key: "value" },+ release: "1.0.0",+ version: "2.0.0",+ },+ },+ {+ id: v4(),+ type: "observation-create",+ timestamp: new Date().toISOString(),+ body: {+ id: generationId,+ traceId: traceId,+ type: "GENERATION",+ name: "generation-name",+ startTime: "2021-01-01T00:00:00.000Z",+ endTime: "2021-01-01T00:00:00.000Z",+ modelParameters: { key: "value" },+ input: { key: "value" },+ metadata: { key: "value" },+ version: "2.0.0",+ },+ },+ {+ id: v4(),+ type: "observation-update",+ timestamp: new Date().toISOString(),+ body: {+ id: generationId,+ type: "GENERATION",+ output: { key: "this is a great gpt output" },+ usage: testConfig.usage,+ },+ },+ {+ id: v4(),+ type: "observation-create",+ timestamp: new Date().toISOString(),+ body: {+ id: spanId,+ traceId: traceId,+ type: "SPAN",+ name: "span-name",+ startTime: "2021-01-01T00:00:00.000Z",+ endTime: "2021-01-01T00:00:00.000Z",+ input: { input: "value" },+ metadata: { meta: "value" },+ version: "2.0.0",+ },+ },+ {+ id: v4(),+ type: "score-create",+ timestamp: new Date().toISOString(),+ body: {+ id: scoreId,+ name: "score-name",+ value: 100.5,+ traceId: traceId,+ },+ },+ ],+ });++ expect(response.status).toBe(207);++ console.log("response body", response.body);++ const dbTrace = await prisma.trace.findMany({+ where: {+ name: "trace-name",+ },+ });++ expect(dbTrace.length).toBeGreaterThan(0);+ expect(dbTrace[0]?.name).toBe("trace-name");+ expect(dbTrace[0]?.release).toBe("1.0.0");+ expect(dbTrace[0]?.externalId).toBeNull();+ expect(dbTrace[0]?.version).toBe("2.0.0");+ expect(dbTrace[0]?.projectId).toBe(+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ );++ const dbGeneration = await prisma.observation.findUnique({+ where: {+ id: generationId,+ },+ });++ expect(dbGeneration?.id).toBe(generationId);+ expect(dbGeneration?.traceId).toBe(traceId);+ expect(dbGeneration?.name).toBe("generation-name");+ expect(dbGeneration?.startTime).toEqual(+ new Date("2021-01-01T00:00:00.000Z"),+ );+ expect(dbGeneration?.endTime).toEqual(+ new Date("2021-01-01T00:00:00.000Z"),+ );+ expect(dbGeneration?.model).toBeNull();+ expect(dbGeneration?.modelParameters).toEqual({ key: "value" });+ expect(dbGeneration?.input).toEqual({ key: "value" });+ expect(dbGeneration?.metadata).toEqual({ key: "value" });+ expect(dbGeneration?.version).toBe("2.0.0");+ expect(dbGeneration?.promptTokens).toEqual(+ testConfig.expectedPromptTokens,+ );+ expect(dbGeneration?.completionTokens).toEqual(+ testConfig.expectedCompletionTokens,+ );+ expect(dbGeneration?.totalTokens).toEqual(testConfig.expectedTotalTokens);+ expect(dbGeneration?.unit).toEqual(testConfig.expectedUnit);+ expect(dbGeneration?.output).toEqual({+ key: "this is a great gpt output",+ });++ const dbSpan = await prisma.observation.findUnique({+ where: {+ id: spanId,+ },+ });++ expect(dbSpan?.id).toBe(spanId);+ expect(dbSpan?.name).toBe("span-name");+ expect(dbSpan?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));+ expect(dbSpan?.endTime).toEqual(new Date("2021-01-:00:00.000Z"));+ expect(dbSpan?.input).toEqual({ input: "value" });+ expect(dbSpan?.metadata).toEqual({ meta: "value" });+ expect(dbSpan?.version).toBe("2.0.0");++ const dbScore = await prisma.score.findUnique({+ where: {+ id: scoreId,+ },+ });++ expect(dbScore?.id).toBe(scoreId);+ expect(dbScore?.traceId).toBe(traceId);+ expect(dbScore?.name).toBe("score-name");+ expect(dbScore?.value).toBe(100.5);+ expect(dbScore?.observationId).toBeNull();+ });+ });++ it("should create and update all events", async () => {const traceId = v4();const generationId = v4();const spanId = v4();+ const eventId = v4();const scoreId = v4();const response = await makeAPICall("POST", "/api/public/ingestion", {@@ -22,55 +236,55 @@ describe("/api/public/ingestion API Endpoint", () => {timestamp: new Date().toISOString(),body: {id: traceId,- name: "trace-name",- userId: "user-1",- metadata: { key: "value" },- release: "1.0.0",- version: "2.0.0",},},{id: v4(),- type: "observation-create",+ type: "span-create",+ timestamp: new Date().toISOString(),+ body: {+ id: spanId,+ traceId: traceId,+ },+ },+ {+ id: v4(),+ type: "span-update",+ timestamp: new Date().toISOString(),+ body: {+ id: spanId,+ traceId: traceId,+ name: "span-name",+ },+ },+ {+ id: v4(),+ type: "generation-create",timestamp: new Date().toISOString(),body: {id: generationId,traceId: traceId,- type: "GENERATION",- name: "generation-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- modelParameters: { key: "value" },- input: { key: "value" },- metadata: { key: "value" },- version: "2.0.0",+ parentObservationId: spanId,},},{id: v4(),- type: "observation-update",+ type: "generation-update",timestamp: new Date().toISOString(),body: {id: generationId,- type: "GENERATION",- output: { key: "this is a great gpt output" },- usage: { promptTokens: 400, completionTokens: 1000 },+ name: "generation-name",},},{id: v4(),- type: "observation-create",+ type: "event-create",timestamp: new Date().toISOString(),body: {- id: spanId,+ id: eventId,traceId: traceId,- type: "SPAN",- name: "span-name",- startTime: "2021-01-01T00:00:00.000Z",- endTime: "2021-01-01T00:00:00.000Z",- input: { input: "value" },- metadata: { meta: "value" },- version: "2.0.0",+ name: "event-name",+ parentObservationId: generationId,},},{@@ -80,8 +294,9 @@ describe("/api/public/ingestion API Endpoint", () => {body: {id: scoreId,name: "score-name",- value: 100.5,traceId: traceId,+ value: 100.5,+ observationId: generationId,},},],@@ -91,17 +306,23 @@ describe("/api/public/ingestion API Endpoint", () => {const dbTrace = await prisma.trace.findMany({where: {- name: "trace-name",+ id: traceId,},});expect(dbTrace.length).toBeGreaterThan(0);- expect(dbTrace[0]?.name).toBe("trace-name");- expect(dbTrace[0]?.release).toBe("1.0.0");- expect(dbTrace[0]?.externalId).toBeNull();- expect(dbTrace[0]?.version).toBe("2.0.0");expect(dbTrace[0]?.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");+ const dbSpan = await prisma.observation.findUnique({+ where: {+ id: spanId,+ },+ });++ expect(dbSpan?.id).toBe(spanId);+ expect(dbSpan?.name).toBe("span-name");+ expect(dbSpan?.traceId).toBe(traceId);+const dbGeneration = await prisma.observation.findUnique({where: {id: generationId,@@ -111,34 +332,18 @@ describe("/api/public/ingestion API Endpoint", () => {expect(dbGeneration?.id).toBe(generationId);expect(dbGeneration?.traceId).toBe(traceId);expect(dbGeneration?.name).toBe("generation-name");- expect(dbGeneration?.startTime).toEqual(- new Date("2021-01-01T00:00:00.000Z"),- );- expect(dbGeneration?.endTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbGeneration?.model).toBeNull();- expect(dbGeneration?.modelParameters).toEqual({ key: "value" });- expect(dbGeneration?.input).toEqual({ key: "value" });- expect(dbGeneration?.metadata).toEqual({ key: "value" });- expect(dbGeneration?.version).toBe("2.0.0");- expect(dbGeneration?.promptTokens).toEqual(400);- expect(dbGeneration?.completionTokens).toEqual(1000);- expect(dbGeneration?.output).toEqual({- key: "this is a great gpt output",- });+ expect(dbGeneration?.parentObservationId).toBe(spanId);- const dbSpan = await prisma.observation.findUnique({+ const dbEvent = await prisma.observation.findUnique({where: {- id: spanId,+ id: eventId,},});- expect(dbSpan?.id).toBe(spanId);- expect(dbSpan?.name).toBe("span-name");- expect(dbSpan?.startTime).toEqual(new Date("2021-01-01T00:00:00.000Z"));- expect(dbSpan?.endTime).toEqual(new Date("2021-01-:00:00.000Z"));- expect(dbSpan?.input).toEqual({ input: "value" });- expect(dbSpan?.metadata).toEqual({ meta: "value" });- expect(dbSpan?.version).toBe("2.0.0");+ expect(dbEvent?.id).toBe(eventId);+ expect(dbEvent?.traceId).toBe(traceId);+ expect(dbEvent?.name).toBe("event-name");+ expect(dbEvent?.parentObservationId).toBe(generationId);const dbScore = await prisma.score.findUnique({where: {@@ -148,9 +353,8 @@ describe("/api/public/ingestion API Endpoint", () => {expect(dbScore?.id).toBe(scoreId);expect(dbScore?.traceId).toBe(traceId);- expect(dbScore?.name).toBe("score-name");+ expect(dbScore?.observationId).toBe(generationId);expect(dbScore?.value).toBe(100.5);- expect(dbScore?.observationId).toBeNull();});it("should upsert threats", async () => {diff --git a/src/features/public-api/server/ingestion-api-schema.ts b/src/features/public-api/server/ingestion-api-schema.tsindex 06935f6e01..378bdb20ae 100644--- a/src/features/public-api/server/ingestion-api-schema.ts+++ b/src/features/public-api/server/ingestion-api-schema.ts@@ -2,7 +2,46 @@ import { ObservationLevel } from "@prisma/client";import { jsonSchema } from "@/src/utils/zod";import { z } from "zod";-export const TraceSchema = z.object({+export const Usage = z.object({+ input: z.number().int().nullish(),+ output: z.number().int().nullish(),+ total: z.number().int().nullish(),+ unit: z.enum(["TOKENS", "CHARACTERS"]).nullable(),+});++const MixedUsage = z.object({+ input: z.number().int().nullish(),+ output: z.number().int().nullish(),+ total: z.number().int().nullish(),+ unit: z.enum(["TOKENS", "CHARACTERS"]).nullish(),+ promptTokens: z.number().int().nullish(),+ completionTokens: z.number().int().nullish(),+ totalTokens: z.number().int().nullish(),+});++export const usage = MixedUsage.nullish()+ // transform mixed usage model input to new one+ .transform((v) => {+ if (!v) {+ return null;+ }+ if ("promptTokens" in v || "completionTokens" in v || "totalTokens" in v) {+ return {+ input: v.promptTokens,+ output: v.completionTokens,+ total: v.totalTokens,+ unit: "TOKENS",+ };+ }+ if ("input" in v || "output" in v || "total" in v || "unit" in v) {+ const unit = v.unit ?? "TOKENS";+ return { ...v, unit };+ }+ })+ // ensure output is always of new usage model+ .pipe(Usage.nullable());++export const TraceBody = z.object({id: z.string().nullish(),name: z.string().nullish(),externalId: z.string().nullish(),@@ -15,7 +54,71 @@ export const TraceSchema = z.object({version: z.string().nullish(),public: z.boolean().nullish(),});-export const SpanPostSchema = z.object({++export const OptionalObservationBody = z.object({+ traceId: z.string().nullish(),+ name: z.string().nullish(),+ startTime: z.string().datetime({ offset: true }).nullish(),+ metadata: jsonSchema.nullish(),+ input: jsonSchema.nullish(),+ output: jsonSchema.nullish(),+ level: z.nativeEnum(ObservationLevel).nullish(),+ statusMessage: z.string().nullish(),+ parentObservationId: z.string().nullish(),+ version: z.string().nullish(),+});++export const CreateEventEvent = OptionalObservationBody.extend({+ id: z.string().nullish(),+});++export const UpdateEventEvent = OptionalObservationBody.extend({+ id: z.string(),+});++export const CreateSpanBody = CreateEventEvent.extend({+ endTime: z.string().datetime({ offset: true }).nullish(),+});++export const UpdateSpanBody = UpdateEventEvent.extend({+ endTime: z.string().datetime({ offset: true }).nullish(),+});++export const CreateGenerationBody = CreateSpanBody.extend({+ completionStartTime: z.string().datetime({ offset: true }).nullish(),+ model: z.string().nullish(),+ modelParameters: z+ .record(+ z.string(),+ z.union([z.string(), z.number(), z.boolean()]).nullish(),+ )+ .nullish(),+ usage: usage,+});++export const UpdateGenerationBody = UpdateSpanBody.extend({+ completionStartTime: z.string().datetime({ offset: true }).nullish(),+ model: z.string().nullish(),+ modelParameters: z+ .record(+ z.string(),+ z.union([z.string(), z.number(), z.boolean()]).nullish(),+ )+ .nullish(),+ usage: usage,+});++export const ScoreBody = z.object({+ id: z.string().nullish(),+ name: z.string(),+ value: z.number(),+ traceId: z.string(),+ observationId: z.string().nullish(),+ comment: z.string().nullish(),+});++// LEGACY, only required for backwards compatibility+export const LegacySpanPostSchema = z.object({id: z.string().nullish(),traceId: z.string().nullish(),name: z.string().nullish(),@@ -30,7 +133,7 @@ export const SpanPostSchema = z.object({version: z.string().nullish(),});-export const SpanPatchSchema = z.object({+export const LegacySpanPatchSchema = z.object({spanId: z.string(),traceId: z.string().nullish(),name: z.string().nullish(),@@ -43,7 +146,8 @@ export const SpanPatchSchema = z.object({statusMessage: z.string().nullish(),version: z.string().nullish(),});-export const GenerationsCreateSchema = z.object({++export const LegacyGenerationsCreateSchema = z.object({id: z.string().nullish(),traceId: z.string().nullish(),name: z.string().nullish(),@@ -59,13 +163,7 @@ export const GenerationsCreateSchema = z.object({.nullish(),prompt: jsonSchema.nullish(),completion: jsonSchema.nullish(),- usage: z- .object({- promptTokens: z.number().nullish(),- completionTokens: z.number().nullish(),- totalTokens: z.number().nullish(),- })- .nullish(),+ usage: usage,metadata: jsonSchema.nullish(),parentObservationId: z.string().nullish(),level: z.nativeEnum(ObservationLevel).nullish(),@@ -73,7 +171,7 @@ export const GenerationsCreateSchema = z.object({version: z.string().nullish(),});-export const GenerationPatchSchema = z.object({+export const LegacyGenerationPatchSchema = z.object({generationId: z.string(),traceId: z.string().nullish(),name: z.string().nullish(),@@ -89,33 +187,14 @@ export const GenerationPatchSchema = z.object({.nullish(),prompt: jsonSchema.nullish(),completion: jsonSchema.nullish(),- usage: z- .object({- promptTokens: z.number().nullish(),- completionTokens: z.number().nullish(),- totalTokens: z.number().nullish(),- })- .nullish(),+ usage: usage,metadata: jsonSchema.nullish(),level: z.nativeEnum(ObservationLevel).nullish(),statusMessage: z.string().nullish(),version: z.string().nullish(),});-export const EventSchema = z.object({- id: z.string().nullish(),- traceId: z.string().nullish(),- name: z.string().nullish(),- startTime: z.string().datetime({ offset: true }).nullish(),- metadata: jsonSchema.nullish(),- input: jsonSchema.nullish(),- output: jsonSchema.nullish(),- level: z.nativeEnum(ObservationLevel).nullish(),- statusMessage: z.string().nullish(),- parentObservationId: z.string().nullish(),- version: z.string().nullish(),-});-export const ObservationSchema = z.object({+export const LegacyObservationBody = z.object({id: z.string().nullish(),traceId: z.string().nullish(),type: z.enum(["GENERATION", "SPAN", "EVENT"]),@@ -132,13 +211,7 @@ export const ObservationSchema = z.object({.nullish(),input: jsonSchema.nullish(),output: jsonSchema.nullish(),- usage: z- .object({- promptTokens: z.number().nullish(),- completionTokens: z.number().nullish(),- totalTokens: z.number().nullish(),- })- .nullish(),+ usage: usage,metadata: jsonSchema.nullish(),parentObservationId: z.string().nullish(),level: z.nativeEnum(ObservationLevel).nullish(),@@ -146,50 +219,79 @@ export const ObservationSchema = z.object({version: z.string().nullish(),});-export const ScoreSchema = z.object({- id: z.string().nullish(),- name: z.string(),- value: z.number(),- traceId: z.string(),- observationId: z.string().nullish(),- comment: z.string().nullish(),-});+// definitions for the ingestion APIexport const eventTypes = {TRACE_CREATE: "trace-create",- OBSERVATION_CREATE: "observation-create",- OBSERVAION_UPDATE: "observation-update",SCORE_CREATE: "score-create",+ EVENT_CREATE: "event-create",+ SPAN_CREATE: "span-create",+ SPAN_UPDATE: "span-update",+ GENERATION_CREATE: "generation-create",+ GENERATION_UPDATE: "generation-update",++ // LEGACY, only required for backwards compatibility+ OBSERVATION_CREATE: "observation-create",+ OBSERVATION_UPDATE: "observation-update",} as const;+const base = z.object({id: z.string(),timestamp: z.string().datetime({ offset: true }),});export const traceEvent = base.extend({type: z.literal(eventTypes.TRACE_CREATE),- body: TraceSchema,+ body: TraceBody,});-export const observationEvent = base.extend({- type: z.literal(eventTypes.OBSERVATION_CREATE),- body: ObservationSchema,++export const eventCreateEvent = base.extend({+ type: z.literal(eventTypes.EVENT_CREATE),+ body: CreateEventEvent,+});+export const spanCreateEvent = base.extend({+ type: z.literal(eventTypes.SPAN_CREATE),+ body: CreateSpanBody,+});+export const spanUpdateEvent = base.extend({+ type: z.literal(eventTypes.SPAN_UPDATE),+ body: UpdateSpanBody,});-export const observationUpdateEvent = base.extend({- type: z.literal(eventTypes.OBSERVAION_UPDATE),- body: ObservationSchema,+export const generationCreateEvent = base.extend({+ type: z.literal(eventTypes.GENERATION_CREATE),+ body: CreateGenerationBody,+});+export const generationUpdateEvent = base.extend({+ type: z.literal(eventTypes.GENERATION_UPDATE),+ body: UpdateGenerationBody,});export const scoreEvent = base.extend({type: z.literal(eventTypes.SCORE_CREATE),- body: ScoreSchema,+ body: ScoreBody,+});+export const legacyObservationCreateEvent = base.extend({+ type: z.literal(eventTypes.OBSERVATION_CREATE),+ body: LegacyObservationBody,});-export const singleEventSchema = z.discriminatedUnion("type", [+export const legacyObservationUpdateEvent = base.extend({+ type: z.literal(eventTypes.OBSERVATION_UPDATE),+ body: LegacyObservationBody,+});++export const ingestionEvent = z.discriminatedUnion("type", [traceEvent,- observationEvent,- observationUpdateEvent,scoreEvent,+ eventCreateEvent,+ spanCreateEvent,+ spanUpdateEvent,+ generationCreateEvent,+ generationUpdateEvent,+ // LEGACY, only required for backwards compatibility+ legacyObservationCreateEvent,+ legacyObservationUpdateEvent,]);-export const ingestionBatch = z.array(singleEventSchema);+export const ingestionBatchEvent = z.array(ingestionEvent);export const ingestionApiSchema = z.object({- batch: ingestionBatch,+ batch: ingestionBatchEvent,});diff --git a/src/features/public-api/server/outputSchemaConversion.ts b/src/features/public-api/server/outputSchemaConversion.tsnew file mode 100644index 0000000000..ec6d217e2d--- /dev/null+++ b/src/features/public-api/server/outputSchemaConversion.ts@@ -0,0 +1,19 @@+import { type Observation } from "@prisma/client";++// This function exists to endure backwards compatibility with GET API consumers+// Old APIs expect to return promptTokens, completionTokens, totalTokens+// New APIs expect to return usage: { input, output, total, unit }+// We decided to return both formats to not break anything. In the future, this function+// will take a variable passed from a query param to determine which API version to return.+export const mapUsageOutput = (observation: Observation) => {+ const { promptTokens, completionTokens, totalTokens, unit } = observation;+ return {+ ...observation,+ usage: {+ unit,+ input: promptTokens,+ output: completionTokens,+ total: totalTokens,+ },+ };+};diff --git a/src/pages/api/public/events.ts b/src/pages/api/public/events.tsindex 01c54df463..e2be1d81c2 100644--- a/src/pages/api/public/events.ts+++ b/src/pages/api/public/events.ts@@ -3,9 +3,9 @@ import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";import { v4 as uuidv4 } from "uuid";import {- EventSchema,+ CreateEventEvent,eventTypes,- ingestionBatch,+ ingestionBatchEvent,} from "@/src/features/public-api/server/ingestion-api-schema";import {handleBatch,@@ -41,7 +41,9 @@ export default async function handler();try {- const convertToObservation = (generation: z.infer<typeof EventSchema>) => {+ const convertToObservation = (+ generation: z.infer<typeof CreateEventEvent>,+ ) => {return {...generation,type: "EVENT",@@ -52,11 +54,11 @@ export default async function handler(id: uuidv4(),type: eventTypes.OBSERVATION_CREATE,timestamp: new Date().toISOString(),- body: convertToObservation(EventSchema.parse(req.body)),+ body: convertToObservation(CreateEventEvent.parse(req.body)),};const result = await handleBatch(- ingestionBatch.parse([event]),+ ingestionBatchEvent.parse([event]),req,authCheck,);diff --git a/src/pages/api/public/generations.ts b/src/pages/api/public/generations.tsindex 46251fc830..733c50289b 100644--- a/src/pages/api/public/generations.ts+++ b/src/pages/api/public/generations.ts@@ -4,10 +4,10 @@ import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/serverimport { v4 as uuidv4 } from "uuid";import { ResourceNotFoundError } from "../../../utils/exceptions";import {- GenerationPatchSchema,- GenerationsCreateSchema,+ LegacyGenerationPatchSchema,+ LegacyGenerationsCreateSchema,eventTypes,- ingestionBatch,+ ingestionBatchEvent,} from "@/src/features/public-api/server/ingestion-api-schema";import {handleBatch,@@ -41,7 +41,7 @@ export default async function handler();const convertToObservation = (- generation: z.infer<typeof GenerationsCreateSchema>,+ generation: z.infer<typeof LegacyGenerationsCreateSchema>,) => {return {...generation,@@ -55,11 +55,13 @@ export default async function handler(id: uuidv4(),type: eventTypes.OBSERVATION_CREATE,timestamp: new Date().toISOString(),- body: convertToObservation(GenerationsCreateSchema.parse(req.body)),+ body: convertToObservation(+ LegacyGenerationsCreateSchema.parse(req.body),+ ),};const result = await handleBatch(- ingestionBatch.parse([event]),+ ingestionBatchEvent.parse([event]),req,authCheck,);@@ -84,7 +86,7 @@ export default async function handler();const convertToObservation = (- generation: z.infer<typeof GenerationPatchSchema>,+ generation: z.infer<typeof LegacyGenerationPatchSchema>,) => {return {...generation,@@ -97,13 +99,13 @@ export default async function handler(const event = {id: uuidv4(),- type: eventTypes.OBSERVAION_UPDATE,+ type: eventTypes.OBSERVATION_UPDATE,timestamp: new Date().toISOString(),- body: convertToObservation(GenerationPatchSchema.parse(req.body)),+ body: convertToObservation(LegacyGenerationPatchSchema.parse(req.body)),};const result = await handleBatch(- ingestionBatch.parse([event]),+ ingestionBatchEvent.parse([event]),req,authCheck,);diff --git a/src/pages/api/public/ingestion.ts b/src/pages/api/public/ingestion.tsindex d2a3a8430d..e7cd1411db 100644--- a/src/pages/api/public/ingestion.ts+++ b/src/pages/api/public/ingestion.ts@@ -9,7 +9,7 @@ import { z } from "zod";import {type ingestionApiSchema,eventTypes,- singleEventSchema,+ ingestionEvent,} from "@/src/features/public-api/server/ingestion-api-schema";import { type ApiAccessScope } from "@/src/features/public-api/server/types";import { persistEventMiddleware } from "@/src/server/api/services/event-service";@@ -61,9 +61,9 @@ export default async function handler(const errors: { id: string; error: unknown }[] = [];- const batch: (z.infer<typeof singleEventSchema> | undefined)[] =+ const batch: (z.infer<typeof ingestionEvent> | undefined)[] =parsedSchema.data.batch.map((event) => {- const parsed = singleEventSchema.safeParse(event);+ const parsed = ingestionEvent.safeParse(event);if (!parsed.success) {errors.push({id:@@ -79,7 +79,7 @@ export default async function handler(return parsed.data;}});- const filteredBatch: z.infer<typeof singleEventSchema>[] =+ const filteredBatch: z.infer<typeof ingestionEvent>[] =batch.filter(isNotNullOrUndefined);await telemetry();@@ -99,17 +99,20 @@ export default async function handler(}}-const sortBatch = (batch: Array<z.infer<typeof singleEventSchema>>) => {- // keep the order of events as they are. Order events in a way that types containing update come last- return batch.sort((a, b) => {- if (a.type === eventTypes.OBSERVAION_UPDATE) {- return 1;- }- if (b.type === eventTypes.OBSERVAION_UPDATE) {- return -1;- }- return 0;- });+const sortBatch = (batch: Array<z.infer<typeof ingestionEvent>>) => {+ // keep the order of events as they are. Order events in a way that types containing updates come last+ // Filter out OBSERVATION_UPDATE events+ const updates = batch.filter(+ (event) => event.type === eventTypes.OBSERVATION_UPDATE,+ );++ // Keep all other events in their original order+ const others = batch.filter(+ (event) => event.type !== eventTypes.OBSERVATION_UPDATE,+ );++ // Return the array with non-update events first, followed by update events+ return [...others, ...updates];};export const handleBatch = async (@@ -171,7 +174,7 @@ export const hasBadRequestError = (errors: Array<unknown>) =>errors.some((error) => error instanceof BadRequestError);const handleSingleEvent = async (- event: z.infer<typeof singleEventSchema>,+ event: z.infer<typeof ingestionEvent>,req: NextApiRequest,apiScope: ApiAccessScope,) => {@@ -180,7 +183,7 @@ const handleSingleEvent = async (JSON.stringify(event, null, 2),);- const cleanedEvent = singleEventSchema.parse(cleanEvent(event));+ const cleanedEvent = ingestionEvent.parse(cleanEvent(event));const { type } = cleanedEvent;@@ -192,7 +195,12 @@ const handleSingleEvent = async (processor = new TraceProcessor(cleanedEvent);break;case eventTypes.OBSERVATION_CREATE:- case eventTypes.OBSERVAION_UPDATE:+ case eventTypes.OBSERVATION_UPDATE:+ case eventTypes.EVENT_CREATE:+ case eventTypes.SPAN_CREATE:+ case eventTypes.SPAN_UPDATE:+ case eventTypes.GENERATION_CREATE:+ case eventTypes.GENERATION_UPDATE:processor = new ObservationProcessor(cleanedEvent);break;case eventTypes.SCORE_CREATE: {@@ -271,6 +279,10 @@ export const handleBatchResult = (}});+ if (returnedErrors.length > 0) {+ console.log("Error processing events", returnedErrors);+ }+results.forEach((result) => {successes.push({id: result.id,diff --git a/src/pages/api/public/observations/[observationId].ts b/src/pages/api/public/observations/[observationId].tsindex a0dd949b40..a04a99c7d5 100644--- a/src/pages/api/public/observations/[observationId].ts+++ b/src/pages/api/public/observations/[observationId].ts@@ -3,6 +3,7 @@ import { z } from "zod";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@/src/server/db";import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";+import { mapUsageOutput } from "@/src/features/public-api/server/outputSchemaConversion";const GetObservationSchema = z.object({observationId: z.string(),@@ -54,7 +55,7 @@ export default async function handler(message: "Observation not found within authorized project",});}- return res.status(200).json(observation);+ return res.status(200).json(mapUsageOutput(observation));} catch (error: unknown) {console.error(error);const errorMessage =diff --git a/src/pages/api/public/observations/index.ts b/src/pages/api/public/observations/index.tsindex ef623b76bf..e6152bdce0 100644--- a/src/pages/api/public/observations/index.ts+++ b/src/pages/api/public/observations/index.ts@@ -1,5 +1,6 @@import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { mapUsageOutput } from "@/src/features/public-api/server/outputSchemaConversion";import { prisma } from "@/src/server/db";import { paginationZod } from "@/src/utils/zod";import { Prisma, type PrismaClient, type Observation } from "@prisma/client";@@ -60,7 +61,7 @@ export default async function handler();return res.status(200).json({- data: observations,+ data: observations.map(mapUsageOutput),meta: {page: searchParams.page,limit: searchParams.limit,@@ -122,6 +123,7 @@ const getObservation = async (o."completion_tokens" AS "completionTokens",o."prompt_tokens" AS "promptTokens",o."total_tokens" AS "totalTokens",+ o."unit" AS "unit",o."version",o."project_id" AS "projectId",o."trace_id" AS "traceId",diff --git a/src/pages/api/public/scores.ts b/src/pages/api/public/scores.tsindex 434932db14..870112746c 100644--- a/src/pages/api/public/scores.ts+++ b/src/pages/api/public/scores.ts@@ -6,9 +6,9 @@ import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";import { paginationZod } from "@/src/utils/zod";import {- ScoreSchema,+ ScoreBody,eventTypes,- ingestionBatch,+ ingestionBatchEvent,} from "@/src/features/public-api/server/ingestion-api-schema";import { v4 } from "uuid";import {@@ -51,11 +51,11 @@ export default async function handler(id: v4(),type: eventTypes.SCORE_CREATE,timestamp: new Date().toISOString(),- body: ScoreSchema.parse(req.body),+ body: ScoreBody.parse(req.body),};const result = await handleBatch(- ingestionBatch.parse([event]),+ ingestionBatchEvent.parse([event]),req,authCheck,);diff --git a/src/pages/api/public/spans.ts b/src/pages/api/public/spans.tsindex c638bec939..9280be2c3e 100644--- a/src/pages/api/public/spans.ts+++ b/src/pages/api/public/spans.ts@@ -4,10 +4,10 @@ import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/serverimport { v4 } from "uuid";import { ResourceNotFoundError } from "../../../utils/exceptions";import {- SpanPatchSchema,- SpanPostSchema,+ LegacySpanPatchSchema,+ LegacySpanPostSchema,eventTypes,- ingestionBatch,+ ingestionBatchEvent,} from "@/src/features/public-api/server/ingestion-api-schema";import {handleBatch,@@ -40,7 +40,9 @@ export default async function handler(JSON.stringify(req.body, null, 2),);- const convertToObservation = (span: z.infer<typeof SpanPostSchema>) => {+ const convertToObservation = (+ span: z.infer<typeof LegacySpanPostSchema>,+ ) => {return {...span,type: "SPAN",@@ -51,11 +53,11 @@ export default async function handler(id: v4(),type: eventTypes.OBSERVATION_CREATE,timestamp: new Date().toISOString(),- body: convertToObservation(SpanPostSchema.parse(req.body)),+ body: convertToObservation(LegacySpanPostSchema.parse(req.body)),};const result = await handleBatch(- ingestionBatch.parse([event]),+ ingestionBatchEvent.parse([event]),req,authCheck,);@@ -78,7 +80,9 @@ export default async function handler(JSON.stringify(req.body, null, 2),);- const convertToObservation = (span: z.infer<typeof SpanPatchSchema>) => {+ const convertToObservation = (+ span: z.infer<typeof LegacySpanPatchSchema>,+ ) => {return {...span,id: span.spanId,@@ -88,13 +92,13 @@ export default async function handler(const event = {id: v4(),- type: eventTypes.OBSERVAION_UPDATE,+ type: eventTypes.OBSERVATION_UPDATE,timestamp: new Date().toISOString(),- body: convertToObservation(SpanPatchSchema.parse(req.body)),+ body: convertToObservation(LegacySpanPatchSchema.parse(req.body)),};const result = await handleBatch(- ingestionBatch.parse([event]),+ ingestionBatchEvent.parse([event]),req,authCheck,);diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.tsindex 48664e6e72..c23bd3402d 100644--- a/src/pages/api/public/traces.ts+++ b/src/pages/api/public/traces.ts@@ -10,7 +10,7 @@ import {handleBatchResultLegacy,} from "@/src/pages/api/public/ingestion";import {- TraceSchema,+ TraceBody,eventTypes,} from "@/src/features/public-api/server/ingestion-api-schema";import { v4 } from "uuid";@@ -52,7 +52,7 @@ export default async function handler(message: "Access denied",});- const body = TraceSchema.parse(req.body);+ const body = TraceBody.parse(req.body);await telemetry();diff --git a/src/pages/api/public/traces/[traceId].ts b/src/pages/api/public/traces/[traceId].tsindex a61848ceae..0fe023443d 100644--- a/src/pages/api/public/traces/[traceId].ts+++ b/src/pages/api/public/traces/[traceId].ts@@ -3,6 +3,7 @@ import { z } from "zod";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@/src/server/db";import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";+import { mapUsageOutput } from "@/src/features/public-api/server/outputSchemaConversion";const GetTraceSchema = z.object({traceId: z.string(),@@ -64,7 +65,9 @@ export default async function handler(message: "Trace not found within authorized project",});}- return res.status(200).json({ ...trace, observations: observations });+ return res+ .status(200)+ .json({ ...trace, observations: observations.map(mapUsageOutput) });} catch (error: unknown) {console.error(error);const errorMessage =diff --git a/src/server/api/services/EventProcessor.ts b/src/server/api/services/EventProcessor.tsindex d6ea2cb3e3..217a59c273 100644--- a/src/server/api/services/EventProcessor.ts+++ b/src/server/api/services/EventProcessor.ts@@ -3,11 +3,16 @@ import { checkApiAccessScope } from "@/src/features/public-api/server/apiScope";import { type ApiAccessScope } from "@/src/features/public-api/server/types";import { AuthenticationError } from "@/src/pages/api/public/ingestion";import {- type observationEvent,+ type legacyObservationCreateEvent,eventTypes,type traceEvent,type scoreEvent,- type observationUpdateEvent,+ type eventCreateEvent,+ type spanCreateEvent,+ type generationCreateEvent,+ type spanUpdateEvent,+ type generationUpdateEvent,+ type legacyObservationUpdateEvent,} from "@/src/features/public-api/server/ingestion-api-schema";import { prisma } from "@/src/server/db";import { ResourceNotFoundError } from "@/src/utils/exceptions";@@ -27,13 +32,23 @@ export interface EventProcessor {}export class ObservationProcessor implements EventProcessor {event:- | z.infer<typeof observationEvent>- | z.infer<typeof observationUpdateEvent>;+ | z.infer<typeof legacyObservationCreateEvent>+ | z.infer<typeof legacyObservationUpdateEvent>+ | z.infer<typeof eventCreateEvent>+ | z.infer<typeof spanCreateEvent>+ | z.infer<typeof spanUpdateEvent>+ | z.infer<typeof generationCreateEvent>+ | z.infer<typeof generationUpdateEvent>;constructor(event:- | z.infer<typeof observationEvent>- | z.infer<typeof observationUpdateEvent>,+ | z.infer<typeof legacyObservationCreateEvent>+ | z.infer<typeof legacyObservationUpdateEvent>+ | z.infer<typeof eventCreateEvent>+ | z.infer<typeof spanCreateEvent>+ | z.infer<typeof spanUpdateEvent>+ | z.infer<typeof generationCreateEvent>+ | z.infer<typeof generationUpdateEvent>,) {this.event = event;}@@ -45,25 +60,26 @@ export class ObservationProcessor implements EventProcessor {}> {const { body } = this.event;- const {- id,- traceId,- type,- name,- startTime,- endTime,- completionStartTime,- model,- modelParameters,- input,- output,- usage,- metadata,- parentObservationId,- level,- statusMessage,- version,- } = body;+ let type;+ switch (this.event.type) {+ case eventTypes.OBSERVATION_CREATE:+ case eventTypes.OBSERVATION_UPDATE:+ type = this.event.body.type;+ break;+ case eventTypes.EVENT_CREATE:+ type = "EVENT" as const;+ break;+ case eventTypes.SPAN_CREATE:+ case eventTypes.SPAN_UPDATE:+ type = "SPAN" as const;+ break;+ case eventTypes.GENERATION_CREATE:+ case eventTypes.GENERATION_UPDATE:+ type = "GENERATION" as const;+ break;+ }++ const { id, traceId, name, startTime, metadata } = body;const existingObservation = id? await prisma.observation.findUnique({@@ -72,7 +88,7 @@ export class ObservationProcessor implements EventProcessor {: null;if (- this.event.type === eventTypes.OBSERVAION_UPDATE &&+ this.event.type === eventTypes.OBSERVATION_UPDATE &&!existingObservation) {throw new ResourceNotFoundError(this.event.id, "Observation not found");@@ -91,10 +107,10 @@ export class ObservationProcessor implements EventProcessor {).id: traceId;- const [newPromptTokens, newCompletionTokens] = this.calculateTokenCounts(- body,- existingObservation ?? undefined,- );+ const [newInputCount, newOutputCount] =+ "usage" in body+ ? this.calculateTokenCounts(body, existingObservation ?? undefined)+ : [undefined, undefined];// merge metadata from existingObservation.metadata and metadataconst mergedMetadata = mergeJson(@@ -113,60 +129,79 @@ export class ObservationProcessor implements EventProcessor {type: type,name: name,startTime: startTime ? new Date(startTime) : undefined,- endTime: endTime ? new Date(endTime) : undefined,- completionStartTime: completionStartTime- ? new Date(completionStartTime)- : undefined,+ endTime:+ "endTime" in body && body.endTime+ ? new Date(body.endTime)+ : undefined,+ completionStartTime:+ "completionStartTime" in body && body.completionStartTime+ ? new Date(body.completionStartTime)+ : undefined,metadata: mergedMetadata ?? metadata ?? undefined,- model: model ?? undefined,- modelParameters: modelParameters ?? undefined,- input: input ?? undefined,- output: output ?? undefined,- promptTokens: newPromptTokens,- completionTokens: newCompletionTokens,+ model: "model" in body ? body.model : undefined,+ modelParameters:+ "modelParameters" in body+ ? body.modelParameters ?? undefined+ : undefined,+ input: body.input ?? undefined,+ output: body.output ?? undefined,+ promptTokens: newInputCount,+ completionTokens: newOutputCount,totalTokens:- usage?.totalTokens ??- (newPromptTokens ?? 0) + (newCompletionTokens ?? 0),- level: level ?? undefined,- statusMessage: statusMessage ?? undefined,- parentObservationId: parentObservationId ?? undefined,- version: version ?? undefined,+ "usage" in body+ ? body.usage?.total ?? (newInputCount ?? 0) + (newOutputCount ?? 0)+ : undefined,+ unit: "usage" in body ? body.usage?.unit ?? undefined : undefined,+ level: body.level ?? undefined,+ statusMessage: body.statusMessage ?? undefined,+ parentObservationId: body.parentObservationId ?? undefined,+ version: body.version ?? undefined,project: { connect: { id: apiScope.projectId } },},update: {- type: type,name,startTime: startTime ? new Date(startTime) : undefined,- endTime: endTime ? new Date(endTime) : undefined,- completionStartTime: completionStartTime- ? new Date(completionStartTime)- : undefined,+ endTime:+ "endTime" in body && body.endTime+ ? new Date(body.endTime)+ : undefined,+ completionStartTime:+ "completionStartTime" in body && body.completionStartTime+ ? new Date(body.completionStartTime)+ : undefined,metadata: mergedMetadata ?? metadata ?? undefined,- model: model ?? undefined,- modelParameters: modelParameters ?? undefined,- input: input ?? undefined,- output: output ?? undefined,- promptTokens: newPromptTokens,- completionTokens: newCompletionTokens,+ model: "model" in body ? body.model : undefined,+ modelParameters:+ "modelParameters" in body+ ? body.modelParameters ?? undefined+ : undefined,+ input: body.input ?? undefined,+ output: body.output ?? undefined,+ promptTokens: newInputCount,+ completionTokens: newOutputCount,totalTokens:- usage?.totalTokens ??- (newPromptTokens ?? 0) + (newCompletionTokens ?? 0),- level: level ?? undefined,- statusMessage: statusMessage ?? undefined,- parentObservationId: parentObservationId ?? undefined,- version: version ?? undefined,+ "usage" in body+ ? body.usage?.total ?? (newInputCount ?? 0) + (newOutputCount ?? 0)+ : undefined,+ unit: "usage" in body ? body.usage?.unit ?? undefined : undefined,+ level: body.level ?? undefined,+ statusMessage: body.statusMessage ?? undefined,+ parentObservationId: body.parentObservationId ?? undefined,+ version: body.version ?? undefined,},};}calculateTokenCounts(- body: z.infer<typeof observationEvent>["body"],+ body:+ | z.infer<typeof legacyObservationCreateEvent>["body"]+ | z.infer<typeof generationCreateEvent>["body"],existingObservation?: Observation,) {const mergedModel = body.model ?? existingObservation?.model;const newPromptTokens =- body.usage?.promptTokens ??+ body?.usage?.input ??((body.input || existingObservation?.input) && mergedModel? tokenCount({model: mergedModel,@@ -175,7 +210,7 @@ export class ObservationProcessor implements EventProcessor {: undefined);const newCompletionTokens =- body.usage?.completionTokens ??+ body?.usage?.output ??((body.output || existingObservation?.output) && mergedModel? tokenCount({model: mergedModel,