🪢 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): upsert and get dataset items (#606)
Marc Klingen86851322c997
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b4cc922311..e3dda72eee 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -73,6 +73,24 @@ RequirementsOn the main branch, we adhere to the best practices of [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/). All pull requests and branches are squash-merged to maintain a clean and readable history. This approach ensures the addition of a conventional commit message when merging contributions.+## Test the public API++The API is tested using Jest. With the development server running, you can run the tests with:++Run all++```bash+npm run test+```++Run interactively in watch mode++```bash+npm run test:watch+```++These tests are also run in CI.+## CI/CDWe use GitHub Actions for CI/CD, the configuration is in [`.github/workflows/pipeline.yml`](.github/workflows/pipeline.yml)diff --git a/fern/apis/server/definition/dataset-items.yml b/fern/apis/server/definition/dataset-items.ymlindex 70fd6fe542..d28e49fb41 100644--- a/fern/apis/server/definition/dataset-items.yml+++ b/fern/apis/server/definition/dataset-items.yml@@ -7,13 +7,23 @@ service:endpoints:create:method: POST- docs: Create a dataset item+ docs: Create a dataset item, upserts on idpath: /dataset-itemsrequest: CreateDatasetItemRequestresponse: commons.DatasetItem+ get:+ docs: Get a specific dataset item+ method: GET+ path: /dataset-items/{id}+ path-parameters:+ id:+ type: string+ response: commons.DatasetItem+types:CreateDatasetItemRequest:properties:datasetName: stringinput: unknownexpectedOutput: optional<unknown>+ id: optional<string>diff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.ymlindex 2cd5195e4a..4e657af864 100644--- a/generated/openapi-server/openapi.yml+++ b/generated/openapi-server/openapi.yml@@ -5,7 +5,7 @@ info:paths:/api/public/dataset-items:post:- description: Create a dataset item+ description: Create a dataset item, upserts on idoperationId: datasetItems_createtags:- DatasetItems@@ -50,6 +50,51 @@ paths:application/json:schema:$ref: '#/components/schemas/CreateDatasetItemRequest'+ /api/public/dataset-items/{id}:+ get:+ description: Get a specific dataset item+ operationId: datasetItems_get+ tags:+ - DatasetItems+ parameters:+ - name: id+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/DatasetItem'+ '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/api/public/dataset-run-items:post:description: Create a dataset run item@@ -1374,6 +1419,9 @@ components:input: {}expectedOutput:nullable: true+ id:+ type: string+ nullable: truerequired:- datasetName- inputdiff --git a/generated/postman/collection.json b/generated/postman/collection.jsonindex bc2f539580..10c362d1fd 100644--- a/generated/postman/collection.json+++ b/generated/postman/collection.json@@ -46,7 +46,7 @@"_type": "endpoint","name": "Create","request": {- "description": "Create a dataset item",+ "description": "Create a dataset item, upserts on id","url": {"raw": "{{baseUrl}}/api/public/dataset-items","host": [@@ -65,7 +65,7 @@"auth": null,"body": {"mode": "raw",- "raw": "{\n \"datasetName\": \"example\",\n \"input\": \"UNKNOWN\",\n \"expectedOutput\": \"UNKNOWN\"\n}",+ "raw": "{\n \"datasetName\": \"example\",\n \"input\": \"UNKNOWN\",\n \"expectedOutput\": \"UNKNOWN\",\n \"id\": \"example\"\n}","options": {"raw": {"language": "json"@@ -74,6 +74,38 @@}},"response": []+ },+ {+ "_type": "endpoint",+ "name": "Get",+ "request": {+ "description": "Get a specific dataset item",+ "url": {+ "raw": "{{baseUrl}}/api/public/dataset-items/:id",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "dataset-items",+ ":id"+ ],+ "query": [],+ "variable": [+ {+ "key": "id",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []}]},diff --git a/src/__tests__/datasets.servertest.ts b/src/__tests__/datasets.servertest.tsnew file mode 100644index 0000000000..f989327126--- /dev/null+++ b/src/__tests__/datasets.servertest.ts@@ -0,0 +1,187 @@+/** @jest-environment node */++import { prisma } from "@/src/server/db";+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";+import { v4 } from "uuid";++describe("/api/public/datasets and /api/public/dataset-items API Endpoints", () => {+ beforeEach(async () => await pruneDatabase());+ afterEach(async () => await pruneDatabase());++ it("should create and get a dataset", async () => {+ await makeAPICall("POST", "/api/public/datasets", {+ name: "dataset-name",+ });++ const dbDataset = await prisma.dataset.findMany({+ where: {+ name: "dataset-name",+ },+ });++ expect(dbDataset.length).toBeGreaterThan(0);++ const getDataset = await makeAPICall(+ "GET",+ `/api/public/datasets/dataset-name`,+ );++ expect(getDataset.status).toBe(200);+ expect(getDataset.body).toMatchObject({+ name: "dataset-name",+ });+ });++ it("should create and get a dataset item (via datasets and individually)", async () => {+ await makeAPICall("POST", "/api/public/datasets", {+ name: "dataset-name",+ });+ await makeAPICall("POST", "/api/public/dataset-items", {+ datasetName: "dataset-name",+ input: { key: "value" },+ expectedOutput: { key: "value" },+ });+ const dbDatasetItem = await prisma.datasetItem.findFirst({+ where: {+ dataset: {+ name: "dataset-name",+ },+ },+ });++ expect(dbDatasetItem).not.toBeNull();++ const getDataset = await makeAPICall(+ "GET",+ `/api/public/datasets/dataset-name`,+ );+ expect(getDataset.status).toBe(200);+ expect(getDataset.body).toMatchObject({+ name: "dataset-name",+ items: [+ {+ id: dbDatasetItem!.id,+ input: { key: "value" },+ expectedOutput: { key: "value" },+ },+ ],+ });++ const getDatasetItem = await makeAPICall(+ "GET",+ `/api/public/dataset-items/${dbDatasetItem!.id}`,+ );+ expect(getDatasetItem.status).toBe(200);+ expect(getDatasetItem.body).toMatchObject({+ id: dbDatasetItem!.id,+ input: { key: "value" },+ expectedOutput: { key: "value" },+ });+ });++ it("should upsert a dataset item", async () => {+ await makeAPICall("POST", "/api/public/datasets", {+ name: "dataset-name",+ });++ const item1 = await makeAPICall("POST", "/api/public/dataset-items", {+ id: "dataset-item-id",+ datasetName: "dataset-name",+ input: { key: "value" },+ });+ expect(item1.status).toBe(200);+ expect(item1.body).toMatchObject({+ id: "dataset-item-id",+ });++ const item2 = await makeAPICall("POST", "/api/public/dataset-items", {+ id: "dataset-item-id",+ datasetName: "dataset-name",+ input: { key: "value2" },+ });+ expect(item2.status).toBe(200);+ expect(item2.body).toMatchObject({+ id: "dataset-item-id",+ input: { key: "value2" },+ });++ const dbDatasetItem = await prisma.datasetItem.findFirst({+ where: { id: "dataset-item-id" },+ });+ expect(dbDatasetItem).not.toBeNull();+ expect(dbDatasetItem?.input).toMatchObject({ key: "value2" });+ });++ it("should create and get a dataset run", async () => {+ const dataset = await makeAPICall("POST", "/api/public/datasets", {+ name: "dataset-name",+ });+ expect(dataset.status).toBe(200);+ expect(dataset.body).toMatchObject({+ name: "dataset-name",+ });+ await makeAPICall("POST", "/api/public/dataset-items", {+ datasetName: "dataset-name",+ id: "dataset-item-id",+ input: { key: "value" },+ expectedOutput: { key: "value" },+ });+ const traceId = v4();+ const observationId = 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: observationId,+ 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",+ },+ },+ ],+ });+ expect(response.status).toBe(207);++ const runItem = await makeAPICall("POST", "/api/public/dataset-run-items", {+ datasetItemId: "dataset-item-id",+ observationId: observationId,+ runName: "run-name",+ });+ const dbRun = await prisma.datasetRuns.findFirst({+ where: {+ name: "run-name",+ },+ });+ expect(dbRun).not.toBeNull();+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ expect(dbRun?.datasetId).toBe(dataset.body.id);+ expect(runItem.status).toBe(200);+ expect(runItem.body).toMatchObject({+ datasetItemId: "dataset-item-id",+ observationId: observationId,+ datasetRunId: dbRun?.id,+ });+ });+});diff --git a/src/__tests__/test-utils.ts b/src/__tests__/test-utils.tsindex ade688cdaa..63b387596b 100644--- a/src/__tests__/test-utils.ts+++ b/src/__tests__/test-utils.ts@@ -9,6 +9,9 @@ export const pruneDatabase = async () => {await prisma.score.deleteMany();await prisma.observation.deleteMany();await prisma.trace.deleteMany();+ await prisma.datasetItem.deleteMany();+ await prisma.dataset.deleteMany();+ await prisma.datasetRuns.deleteMany();};export function createBasicAuthHeader(@@ -24,7 +27,7 @@ export function createBasicAuthHeader(export async function makeAPICall(method: "POST" | "GET" | "PUT" | "DELETE" | "PATCH",url: string,- body: unknown,+ body?: unknown,) {const finalUrl = `http://localhost:3000/${url}`;const options = {@@ -37,7 +40,9 @@ export async function makeAPICall("sk-lf-1234567890",),},- body: JSON.stringify(body),+ // Conditionally include the body property if the method is not "GET"+ ...(method !== "GET" &&+ body !== undefined && { body: JSON.stringify(body) }),};const a = await fetch(finalUrl, options);diff --git a/src/pages/api/public/dataset-items.ts b/src/pages/api/public/dataset-items.tsindex 723154f801..3a98a582d1 100644--- a/src/pages/api/public/dataset-items.ts+++ b/src/pages/api/public/dataset-items.ts@@ -4,11 +4,13 @@ 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 { jsonSchema } from "@/src/utils/zod";+import { v4 as uuidv4 } from "uuid";const CreateDatasetItemSchema = z.object({datasetName: z.string(),input: jsonSchema,expectedOutput: jsonSchema.nullish(),+ id: z.string().nullish(),});export default async function handler(@@ -30,14 +32,13 @@ export default async function handler(try {if (req.method === "POST") {console.log(- "Trying to create dataset, project ",+ "Trying to upsert dataset item, project ",authCheck.scope.projectId,", body:",JSON.stringify(req.body, null, 2),);- const { datasetName, input, expectedOutput } =- CreateDatasetItemSchema.parse(req.body);+ const itemBody = CreateDatasetItemSchema.parse(req.body);// CHECK ACCESS SCOPEif (authCheck.scope.accessLevel !== "all")@@ -50,7 +51,7 @@ export default async function handler(const dataset = await prisma.dataset.findFirst({where: {projectId: authCheck.scope.projectId,- name: datasetName,+ name: itemBody.datasetName,},});if (!dataset) {@@ -58,16 +59,30 @@ export default async function handler(message: "Dataset not found",});}+ const id = itemBody.id ?? uuidv4();- const item = await prisma.datasetItem.create({- data: {- input,- expectedOutput: expectedOutput ?? undefined,+ const item = await prisma.datasetItem.upsert({+ where: {+ id,+ datasetId: dataset.id,+ },+ create: {+ id,+ input: itemBody.input,+ expectedOutput: itemBody.expectedOutput ?? undefined,datasetId: dataset.id,},+ update: {+ input: itemBody.input,+ expectedOutput: itemBody.expectedOutput ?? undefined,+ },});res.status(200).json(item);+ } else {+ res.status(405).json({+ message: "Method not allowed",+ });}} catch (error: unknown) {console.error(error);diff --git a/src/pages/api/public/dataset-items/[datasetItemId].ts b/src/pages/api/public/dataset-items/[datasetItemId].tsnew file mode 100644index 0000000000..df3464c798--- /dev/null+++ b/src/pages/api/public/dataset-items/[datasetItemId].ts@@ -0,0 +1,76 @@+import { type NextApiRequest, type NextApiResponse } from "next";+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";++const GetDatasetItemQuerySchema = z.object({+ datasetItemId: z.string(),+});++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ await runMiddleware(req, res, cors);++ // CHECK AUTH+ const authCheck = await verifyAuthHeaderAndReturnScope(+ req.headers.authorization,+ );+ if (!authCheck.validKey)+ return res.status(401).json({+ message: authCheck.error,+ });+ // END CHECK AUTH++ try {+ if (req.method === "GET") {+ console.log(+ "Trying to get dataset item, project ",+ authCheck.scope.projectId,+ ", body:",+ JSON.stringify(req.body, null, 2),+ ", query:",+ JSON.stringify(req.query, null, 2),+ );++ const { datasetItemId } = GetDatasetItemQuerySchema.parse(req.query);++ // CHECK ACCESS SCOPE+ if (authCheck.scope.accessLevel !== "all")+ return res.status(403).json({+ message: "Access denied",+ });+ // END CHECK ACCESS SCOPE++ // Check access to dataset+ const datasetItem = await prisma.datasetItem.findFirst({+ where: {+ id: datasetItemId,+ dataset: {+ projectId: authCheck.scope.projectId,+ },+ },+ });+ if (!datasetItem) {+ return res.status(404).json({+ message: "Dataset item not found (for this project)",+ });+ }+ res.status(200).json(datasetItem);+ } else {+ res.status(405).json({+ message: "Method not allowed",+ });+ }+ } catch (error: unknown) {+ console.error(error);+ const errorMessage =+ error instanceof Error ? error.message : "An unknown error occurred";+ res.status(400).json({+ message: "Invalid request data",+ error: errorMessage,+ });+ }+}