🪢 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: improve clickhouse seeder (#3853)
Max Deichmannd99f12fe64f2
diff --git a/packages/shared/clickhouse/scripts/seed.ts b/packages/shared/clickhouse/scripts/seed.tsindex f8576458d3..a91f6e5d39 100644--- a/packages/shared/clickhouse/scripts/seed.ts+++ b/packages/shared/clickhouse/scripts/seed.ts@@ -1,117 +1,7 @@import { clickhouseClient } from "@langfuse/shared/src/server";import { prisma } from "../../src/db";import { redis } from "@langfuse/shared/src/server";--export const prepareClickhouse = async (projectIds: string[]) => {- for (const projectId of projectIds) {- console.log(`Preparing Clickhouse for project ${projectId}...`);- const tracesQuery = `- INSERT INTO traces- SELECT toString(floor(randUniform(0, 10000))) AS id,- '2024-07-31 09:47:59.270' AS timestamp,- concat('name_', toString(rand() % 100)) AS name,- concat('user_id_', toString(randUniform(0, 100))) AS user_id,- map('key', 'value') AS metadata,- concat('release_', toString(randUniform(0, 100))) AS release,- concat('version_', toString(randUniform(0, 100))) AS version,- '${projectId}' AS project_id,- if(rand() < 0.8, true, false) as public,- if(rand() < 0.8, true, false) as bookmarked,- array('tag1', 'tag2') as tags,- repeat('input', toInt64(randExponential(1 / 100))) AS input,- repeat('output', toInt64(randExponential(1 / 100))) AS output,- concat('session_', toString(rand() % 100)) AS session_id,- timestamp AS created_at,- timestamp AS updated_at,- timestamp AS event_ts- FROM numbers(10000);- `;-- const observationsQuery = `- INSERT INTO observations- SELECT toString(floor(randUniform(0, 70000))) AS id,- toString(floor(randUniform(0, 10000))) AS trace_id,- '${projectId}' AS project_id,- 'GENERATION' AS type,- toString(rand()) AS parent_observation_id,- '2024-07-31 09:47:59.270' AS start_time,- addSeconds(start_time, floor(randExponential(1 / 10))) AS end_time,- concat('name', toString(rand() % 100)) AS name,- map('key', 'value') AS metadata,- 'level' AS level,- 'status_message' AS status_message,- 'version' AS version,- repeat('input', toInt64(randExponential(1 / 100))) AS input,- repeat('output', toInt64(randExponential(1 / 100))) AS output,- if(- number % 2 = 0,- 'claude-3-haiku-20240307',- 'gpt-4'- ) as provided_model_name,- toString(floor(randUniform(0, 1000000000))) as internal_model_id,- 'model_parameters' AS model_parameters,- 1000 AS provided_input_usage_units,- 1000 AS provided_output_usage_units,- 1000 AS provided_total_usage_units,- 1000 AS input_usage_units,- 1000 AS output_usage_units,- 1000 AS total_usage_units,- 1000 AS provided_input_cost,- 1000 AS provided_output_cost,- 1000 AS provided_total_cost,- 'unit' AS unit,- 1000 AS input_cost,- 1000 AS output_cost,- 1000 AS total_cost,- start_time AS completion_start_time,- toString(rand()) AS prompt_id,- toString(rand()) AS prompt_name,- 1000 AS prompt_version,- start_time AS created_at,- start_time AS updated_at,- start_time AS event_ts- FROM numbers(10000);- `;-- const scoresQuery = `- INSERT INTO scores- SELECT toString(floor(randUniform(0, 100))) AS id,- now() - randUniform(0, 100) AS timestamp,- '${projectId}' AS project_id,- toString(floor(randUniform(0, 1000))) AS trace_id,- if(- rand() > 0.9,- toString(floor(randUniform(0, 1000))),- NULL- ) AS observation_id,- concat('name_', toString(rand() % 100)) AS name,- randUniform(0, 100) as value,- 'API' as source,- 'comment' as comment,- toString(rand() % 100) as author_user_id,- toString(rand() % 100) as config_id,- toString(rand() % 100) as data_type,- toString(rand() % 100) as string_value,- timestamp AS created_at,- timestamp AS updated_at,- timestamp AS event_ts- FROM numbers(10000);- `;-- const queries = [tracesQuery, scoresQuery, observationsQuery];-- await Promise.all(- queries.map((query) =>- clickhouseClient.command({- query,- clickhouse_settings: {- wait_end_of_query: 1,- },- })- )- );- }-};+import { prepareClickhouse } from "../../scripts/prepareClickhouse";async function main() {try {@@ -119,7 +9,11 @@ async function main() {"7a88fb47-b4e2-43b8-a06c-a5ce950dc53a","239ad00f-562f-411d-af14-831c75ddd875",]; // Example project IDs- await prepareClickhouse(projectIds);+ await prepareClickhouse(projectIds, {+ numberOfDays: 3,+ totalObservations: 1000,+ });+console.log("Clickhouse preparation completed successfully.");} catch (error) {console.error("Error during Clickhouse preparation:", error);diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex bd5d7f2f5b..f306edf68f 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -48,7 +48,8 @@"ch:down": "bash clickhouse/scripts/down.sh","ch:drop": "bash clickhouse/scripts/drop.sh","ch:reset": "pnpm run ch:down && pnpm run ch:up && pnpm run ch:seed",- "ch:seed": "dotenv -e ../../.env -- tsx clickhouse/scripts/seed.ts"+ "ch:seed": "dotenv -e ../../.env -- tsx clickhouse/scripts/seed.ts",+ "load:setup": "dotenv -e ../../.env -- tsx scripts/load-seed.ts"},"prisma": {"seed": "ts-node -r tsconfig-paths/register -r dotenv/config --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"diff --git a/packages/shared/scripts/load-seed.ts b/packages/shared/scripts/load-seed.tsnew file mode 100644index 0000000000..79503ee0f3--- /dev/null+++ b/packages/shared/scripts/load-seed.ts@@ -0,0 +1,133 @@+import { randomUUID } from "crypto";+import { prisma } from "../src/db";+import {+ clickhouseClient,+ getDisplaySecretKey,+ hashSecretKey,+ logger,+} from "../src/server";+import { prepareClickhouse } from "./prepareClickhouse";+import { redis } from "@langfuse/shared/src/server";++const createRandomProjectId = () => randomUUID().toString();++const prepareProjectsAndApiKeys = async (+ numOfProjects: number,+ opts: { requiredProjectIds: string[] }+) => {+ const { requiredProjectIds } = opts;+ const projectsToCreate = numOfProjects - requiredProjectIds.length;+ const projectIds = [...requiredProjectIds];++ for (let i = 0; i < projectsToCreate; i++) {+ projectIds.push(createRandomProjectId());+ }++ const operations = projectIds.map(async (projectId) => {+ const orgId = `org-${projectId}`;++ await prisma.organization.upsert({+ where: { id: orgId },+ update: {},+ create: {+ id: orgId,+ name: `Organization for ${projectId}`,+ },+ });++ await prisma.project.upsert({+ where: { id: projectId },+ update: {},+ create: {+ id: projectId,+ name: `Project ${projectId}`,+ orgId: orgId,+ },+ });++ const apiKeyId = `api-key-${projectId}`;+ const apiKeyExists = await prisma.apiKey.findUnique({+ where: { id: apiKeyId },+ });+ if (!apiKeyExists) {+ const sk = await hashSecretKey(+ `sk-${Math.random().toString(36).substr(2, 9)}`+ );+ await prisma.apiKey.create({+ data: {+ id: apiKeyId,+ note: `API Key for ${projectId}`,+ publicKey: `pk-${Math.random().toString(36).substr(2, 9)}`,+ hashedSecretKey: sk,+ displaySecretKey: getDisplaySecretKey(sk),+ project: {+ connect: {+ id: projectId,+ },+ },+ },+ });+ }+ });++ await Promise.all(operations);+ return projectIds;+};++async function main() {+ let numOfProjects = parseInt(process.argv[3], 10);+ let numberOfDays = parseInt(process.argv[4], 10);+ let totalObservations = parseInt(process.argv[5], 10);++ if (isNaN(totalObservations)) {+ logger.warn(+ "Total observations not provided or invalid. Defaulting to 1000 observations."+ );+ totalObservations = 1000;+ }++ if (isNaN(numOfProjects)) {+ logger.warn(+ "Number of projects not provided or invalid. Defaulting to 10 projects."+ );+ numOfProjects = 10;+ }++ if (isNaN(numberOfDays)) {+ logger.warn(+ "Number of days not provided or invalid. Defaulting to 3 days."+ );+ numberOfDays = 3;+ }++ logger.info(+ `Preparing Clickhouse for ${numOfProjects} projects and ${numberOfDays} days with max Observations ${totalObservations}.`+ );++ try {+ const projectIds = [+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ "239ad00f-562f-411d-af14-831c75ddd875",+ ];++ const createdProjectIds = await prepareProjectsAndApiKeys(numOfProjects, {+ requiredProjectIds: projectIds,+ });++ await prepareClickhouse(createdProjectIds, {+ numberOfDays,+ totalObservations: totalObservations ?? 1000,+ });++ logger.info("Clickhouse preparation completed successfully.");+ } catch (error) {+ logger.error("Error during Clickhouse preparation:", error);+ } finally {+ await clickhouseClient.close();+ await prisma.$disconnect();+ redis?.disconnect();+ logger.info("Disconnected from Clickhouse.");+ }+}++main();diff --git a/packages/shared/scripts/prepareClickhouse.ts b/packages/shared/scripts/prepareClickhouse.tsnew file mode 100644index 0000000000..1a3c5d7767--- /dev/null+++ b/packages/shared/scripts/prepareClickhouse.ts@@ -0,0 +1,220 @@+import { clickhouseClient, logger } from "../src/server";++function randn_bm(min: number, max: number, skew: number) {+ let u = 0,+ v = 0;+ while (u === 0) u = Math.random(); //Converting [0,1) to (0,1)+ while (v === 0) v = Math.random();+ let num = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);++ num = num / 10.0 + 0.5; // Translate to 0 -> 1+ if (num > 1 || num < 0)+ num = randn_bm(min, max, skew); // resample between 0 and 1 if out of range+ else {+ num = Math.pow(num, skew); // Skew+ num *= max - min; // Stretch to fill range+ num += min; // offset to min+ }+ return num;+}++export const prepareClickhouse = async (+ projectIds: string[],+ opts: {+ numberOfDays: number;+ totalObservations: number;+ }+) => {+ logger.info(+ `Preparing Clickhouse for ${projectIds.length} projects and ${opts.numberOfDays} days.`+ );++ const projectData = projectIds.map((projectId) => {+ const observationsPerProject = Math.ceil(+ randn_bm(0, opts.totalObservations, 2)+ ); // Skew the number of observations++ const tracesPerProject = Math.floor(observationsPerProject / 6); // On average, one trace should have 6 observations+ const scoresPerProject = tracesPerProject * 10; // On average, one trace should have 10 scores+ return {+ projectId,+ observationsPerProject,+ tracesPerProject,+ scoresPerProject,+ };+ });++ for (const data of projectData) {+ const {+ projectId,+ tracesPerProject,+ observationsPerProject,+ scoresPerProject,+ } = data;+ logger.info(+ `Preparing Clickhouse for ${projectId}: Traces: ${tracesPerProject}, Scores: ${scoresPerProject}, Observations: ${observationsPerProject}`+ );++ const tracesQuery = `+ INSERT INTO traces+ SELECT toString(number) AS id,+ toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS timestamp,+ concat('name_', toString(rand() % 100)) AS name,+ concat('user_id_', toString(randUniform(0, 100))) AS user_id,+ map('key', 'value') AS metadata,+ concat('release_', toString(randUniform(0, 100))) AS release,+ concat('version_', toString(randUniform(0, 100))) AS version,+ '${projectId}' AS project_id,+ if(rand() < 0.8, true, false) as public,+ if(rand() < 0.8, true, false) as bookmarked,+ array('tag1', 'tag2') as tags,+ repeat('input', toInt64(randExponential(1 / 100))) AS input,+ repeat('output', toInt64(randExponential(1 / 100))) AS output,+ concat('session_', toString(rand() % 100)) AS session_id,+ timestamp AS created_at,+ timestamp AS updated_at,+ timestamp AS event_ts+ FROM numbers(${tracesPerProject});+ `;++ const observationsQuery = `+ INSERT INTO observations+ SELECT toString(number) AS id,+ toString(floor(randUniform(0, ${tracesPerProject}))) AS trace_id,+ '${projectId}' AS project_id,+ if(rand() < 0.47, 'GENERATION', if(rand() < 0.94, 'SPAN', 'EVENT')) AS type,+ toString(rand()) AS parent_observation_id,+ toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS start_time,+ addSeconds(start_time, if(rand() < 0.6, floor(randUniform(0, 20)), floor(randUniform(0, 3600)))) AS end_time,+ concat('name', toString(rand() % 100)) AS name,+ map('key', 'value') AS metadata,+ if(rand() < 0.9, 'DEFAULT', if(rand() < 0.5, 'ERROR', if(rand() < 0.5, 'DEBUG', 'WANING'))) AS level,+ 'status_message' AS status_message,+ 'version' AS version,+ repeat('input', toInt64(randExponential(1 / 100))) AS input,+ repeat('output', toInt64(randExponential(1 / 100))) AS output,+ case+ when number % 2 = 0 then 'claude-3-haiku-20240307'+ else 'gpt-4'+ end as provided_model_name,+ case+ when number % 2 = 0 then 'cltr0w45b000008k1407o9qv1'+ else 'clrntkjgy000f08jx79v9g1xj'+ end as internal_model_id,+ 'model_parameters' AS model_parameters,+ toInt32(randUniform(0, 1000)) AS provided_input_usage_units,+ toInt32(randUniform(0, 1000)) AS provided_output_usage_units,+ toInt32(randUniform(0, 1000)) AS provided_total_usage_units,+ toInt32(randUniform(0, 1000)) AS input_usage_units,+ toInt32(randUniform(0, 1000)) AS output_usage_units,+ toInt32(randUniform(0, 1000)) AS total_usage_units,+ toInt32(randUniform(0, 1000)) AS provided_input_cost,+ toInt32(randUniform(0, 1000)) AS provided_output_cost,+ toInt32(randUniform(0, 1000)) AS provided_total_cost,+ 'TOKENS' AS unit,+ toInt32(randUniform(0, 1000)) AS input_cost,+ toInt32(randUniform(0, 1000)) AS output_cost,+ toInt32(randUniform(0, 1000)) AS total_cost,+ start_time AS completion_start_time,+ toString(rand()) AS prompt_id,+ toString(rand()) AS prompt_name,+ 1000 AS prompt_version,+ start_time AS created_at,+ start_time AS updated_at,+ start_time AS event_ts+ FROM numbers(${observationsPerProject});+ `;++ const scoresQuery = `+ INSERT INTO scores+ SELECT toString(floor(randUniform(0, 100))) AS id,+ toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS timestamp,+ '${projectId}' AS project_id,+ toString(floor(randUniform(0, ${tracesPerProject}))) AS trace_id,+ if(+ rand() > 0.9,+ toString(floor(randUniform(0, ${observationsPerProject}))),+ NULL+ ) AS observation_id,+ concat('name_', toString(rand() % 100)) AS name,+ randUniform(0, 100) as value,+ 'API' as source,+ 'comment' as comment,+ toString(rand() % 100) as author_user_id,+ toString(rand() % 100) as config_id,+ toString(rand() % 100) as data_type,+ toString(rand() % 100) as string_value,+ timestamp AS created_at,+ timestamp AS updated_at,+ timestamp AS event_ts+ FROM numbers(${scoresPerProject});+ `;++ const queries = [tracesQuery, scoresQuery, observationsQuery];++ for (const query of queries) {+ logger.info(`Executing query: ${query}`);+ await clickhouseClient.command({+ query,+ clickhouse_settings: {+ wait_end_of_query: 1,+ },+ });+ }+ }++ const tables = ["traces", "scores", "observations"];+ for (const table of tables) {+ const query = `+ SELECT+ project_id,+ count() AS per_project_count,+ bar(per_project_count, 0, (+ SELECT count(*)+ FROM ${table}+ ), 50) AS bar_representation+ FROM ${table}+ GROUP BY project_id+ ORDER BY count() desc+ `;++ const result = await clickhouseClient.query({+ query,+ format: "TabSeparated",+ });++ logger.info(+ `${table.charAt(0).toUpperCase() + table.slice(1)} per Project:`+ );+ logger.info(await result.text());+ }++ const tablesWithDateColumns = [+ { name: "traces", dateColumn: "timestamp" },+ { name: "scores", dateColumn: "timestamp" },+ { name: "observations", dateColumn: "start_time" },+ ];++ for (const { name: table, dateColumn } of tablesWithDateColumns) {+ const query = `+ SELECT+ toDate(${dateColumn}) AS event_date,+ count() AS per_date_count,+ bar(per_date_count, 0, (+ SELECT count(*)+ FROM ${table}+ ), 50) AS bar_representation+ FROM ${table}+ GROUP BY event_date+ ORDER BY event_date desc+ `;++ const result = await clickhouseClient.query({+ query,+ format: "TabSeparated",+ });++ logger.info(`${table.charAt(0).toUpperCase() + table.slice(1)} per Date:`);+ logger.info(await result.text());+ }+};