Files
upstream-twenty/packages/twenty-server/scripts/ai-catalog-sync/utils/fetch-artificial-analysis-benchmarks.util.ts
upstream-mirror e7da97194a
Some checks failed
App Prod-Parity E2E Dispatch / dispatch (push) Failing after 10s
CD Storybook UI / build (push) Failing after 3m25s
CD Storybook UI / dispatch (push) Has been skipped
CD deploy main / website-changed-files (push) Successful in 18m8s
CI Agent Skills / changed-files-check (push) Successful in 18m9s
CI Create App E2E minimal / changed-files-check (push) Successful in 24s
CI Create App / changed-files-check (push) Successful in 26s
CI Docs / changed-files-check (push) Successful in 26s
CI Emails / changed-files-check (push) Successful in 28s
CI Example App Hello World / changed-files-check (push) Successful in 23s
CI Front / changed-files-check (push) Has been skipped
CI Example App Postcard / changed-files-check (push) Successful in 27s
CI UI / changed-files-check (push) Has been skipped
CI Utils Test / changed-files-check (push) Successful in 45s
CI Twenty Apps / discover (push) Successful in 1m3s
CD deploy main / deploy-main (push) Failing after 3s
CI Agent Skills / agent-skills-validate (push) Has been skipped
CI Create App / create-app-test (lint) (push) Has been skipped
CI Emails / emails-test (push) Has been skipped
CI Front / front-task (lingui:compile) (push) Has been skipped
CI Front / front-task (lint) (push) Has been skipped
CI Example App Postcard / example-app-postcard (push) Has been skipped
CI UI / ui-task (lint) (push) Has been skipped
CI UI / ui-task (pack-size) (push) Has been skipped
CI UI / ui-task (size) (push) Has been skipped
CI UI / ui-task (test) (push) Has been skipped
CI UI / ui-task (typecheck) (push) Has been skipped
CI Utils Test / utils-test (push) Has been skipped
CI Twenty Apps / ${{ matrix.app.name }} (push) Has been skipped
CI Emails / ci-emails-status-check (push) Successful in 2s
CI Example App Hello World / ci-example-app-hello-world-status-check (push) Successful in 2s
CI Example App Postcard / ci-example-app-postcard-status-check (push) Successful in 3s
CI UI / ui-sb-test (push) Has been skipped
CI Utils Test / ci-utils-test-status-check (push) Successful in 2s
CI Twenty Apps / ci-twenty-apps-status-check (push) Successful in 2s
CI UI / ci-ui-status-check (push) Successful in 2s
CI Desktop / desktop (push) Failing after 1m8s
Push docs to Crowdin / Push documentation to Crowdin (push) Failing after 55s
Push translations to Crowdin / Extract and upload translations (push) Failing after 5s
Push website translations to Crowdin / Extract and upload website translations (push) Failing after 5s
CI Create App / create-app-test (test) (push) Has been skipped
CI Create App / create-app-test (typecheck) (push) Has been skipped
CI Docs / docs-lint (push) Has been skipped
CI Example App Hello World / example-app-hello-world (push) Has been skipped
CI Front / front-task (lingui:extract) (push) Has been skipped
CI Front / front-task (test) (push) Has been skipped
CI Front / front-task (typecheck) (push) Has been skipped
CI UI / ui-sb-build (push) Failing after 1m32s
CI Twenty Apps / ${{ matrix.app.name }} (${{ matrix.server-source }}) (push) Has been skipped
CI Agent Skills / agent-skills-publish (push) Has been skipped
CI Create App / ci-create-app-status-check (push) Successful in 2s
CI Agent Skills / agent-skills-remote-source (push) Has been skipped
CI Create App E2E minimal / create-app-e2e-minimal (push) Has been cancelled
CI E2E Main / e2e-test (push) Has been cancelled
CI Front / front-sb-build (push) Has been cancelled
CI Front / front-build (push) Has been cancelled
CI Create App E2E minimal / ci-create-app-e2e-minimal-status-check (push) Has been cancelled
CI E2E Main / ci-e2e-main-status-check (push) Has been cancelled
CI E2E Main / notify-main-ci-failure (push) Has been cancelled
CI E2E Main / qa-scout-comment (push) Has been cancelled
CI Front / front-sb-test (push) Has been cancelled
CI Front / front-sb-screenshots (push) Has been cancelled
CI Front / ci-front-status-check (push) Has been cancelled
DPA Sub-Processor Sync / sync-subprocessors (push) Failing after 3s
AI Catalog Sync / sync-catalog (push) Failing after 2s
snapshot of https://github.com/twentyhq/twenty.git (main, 2026-09-17; blobs > 131072B omitted)
2026-09-17 23:28:13 +05:00

220 lines
6.1 KiB
TypeScript

import { isDefined } from 'twenty-shared/utils';
import { buildEffortLookupKey } from './build-effort-lookup-key.util';
import { normalizeModelName } from './normalize-model-name.util';
import { parseArtificialAnalysisEffort } from './parse-artificial-analysis-effort.util';
import { type BenchmarkIndex } from '../types/benchmark-index.type';
import { type BenchmarkRecord } from '../types/benchmark-record.type';
const DEFAULT_ARTIFICIAL_ANALYSIS_API_URL =
'https://artificialanalysis.ai/api/v2/language/models/free';
const PAGE_SIZE = 200;
type ArtificialAnalysisModel = Record<string, unknown> & {
id?: string;
slug?: string;
name?: string;
};
type ArtificialAnalysisPage = {
data?: unknown;
pagination?: { has_more?: unknown };
};
// This endpoint returns 0 for "not measured", and a zero tokens-per-second is a
// lie rather than a datum.
const readPositiveNumber = (value: unknown): number | undefined =>
typeof value === 'number' && Number.isFinite(value) && value > 0
? value
: undefined;
const readNested = ({
model,
path,
}: {
model: ArtificialAnalysisModel;
path: string[];
}): number | undefined => {
let current: unknown = model;
for (const key of path) {
if (typeof current !== 'object' || current === null) {
return undefined;
}
current = (current as Record<string, unknown>)[key];
}
return readPositiveNumber(current);
};
const readModels = (page: ArtificialAnalysisPage): ArtificialAnalysisModel[] =>
Array.isArray(page.data) ? (page.data as ArtificialAnalysisModel[]) : [];
// How much a row actually says. The endpoint carries several rows per model and
// some hosts publish no measurements at all, so an unmeasured row must never
// displace a measured one under the same key.
const informationScore = (record: BenchmarkRecord): number =>
[
record.intelligenceIndex,
record.outputTokensPerSecond,
record.costPerTask,
].filter(isDefined).length;
// The rows for one model are the same model at different reasoning efforts, and
// the publisher spells the effort only inside a display name. Taking the
// best-scoring row gives every model its ceiling, measured the same way, which
// is the whole reason for standing on one publisher. Picking by how populated a
// row happened to be scored Sonnet 4.6 at low effort against Sonnet 5 at max,
// and the gap read as a capability difference.
const preferOver = (
candidate: BenchmarkRecord,
existing: BenchmarkRecord,
): boolean => {
const candidateIndex = candidate.intelligenceIndex ?? -1;
const existingIndex = existing.intelligenceIndex ?? -1;
if (candidateIndex !== existingIndex) {
return candidateIndex > existingIndex;
}
return informationScore(candidate) > informationScore(existing);
};
const fetchPage = async ({
url,
apiKey,
page,
}: {
url: string;
apiKey: string;
page: number;
}): Promise<ArtificialAnalysisPage> => {
const pageUrl = new URL(url);
pageUrl.searchParams.set('page', String(page));
pageUrl.searchParams.set('page_size', String(PAGE_SIZE));
const response = await fetch(pageUrl, {
headers: { 'x-api-key': apiKey },
signal: AbortSignal.timeout(60000),
});
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
return (await response.json()) as ArtificialAnalysisPage;
};
// The list is paginated and the free tier allows ten requests a day, so every
// page is read in one run rather than spread across runs.
const fetchAllModels = async ({
url,
apiKey,
}: {
url: string;
apiKey: string;
}): Promise<ArtificialAnalysisModel[]> => {
const models: ArtificialAnalysisModel[] = [];
for (let page = 1; ; page += 1) {
const response = await fetchPage({ url, apiKey, page });
models.push(...readModels(response));
if (response.pagination?.has_more !== true) {
return models;
}
}
};
export const fetchArtificialAnalysisBenchmarks = async (
apiKey: string,
): Promise<BenchmarkIndex> => {
const url =
process.env.ARTIFICIAL_ANALYSIS_API_URL ??
DEFAULT_ARTIFICIAL_ANALYSIS_API_URL;
const models = await fetchAllModels({ url, apiKey });
if (models.length === 0) {
throw new Error(`No models in response from ${url}`);
}
const index: BenchmarkIndex = new Map();
const file = (key: string, record: BenchmarkRecord): void => {
const existing = index.get(key);
if (!isDefined(existing) || preferOver(record, existing)) {
index.set(key, record);
}
};
for (const model of models) {
// One malformed row must not cost us every measurement in the response.
if (typeof model !== 'object' || model === null) {
continue;
}
const aliases = [model.slug, model.id, model.name].filter(isDefined);
// Cost per task is the price of one task of the intelligence index run at
// this row's effort, so it reflects reasoning volume where per-token
// pricing cannot.
const record: BenchmarkRecord = {
intelligenceIndex: readNested({
model,
path: ['evaluations', 'artificial_analysis_intelligence_index'],
}),
outputTokensPerSecond: readNested({
model,
path: ['performance', 'median_output_tokens_per_second'],
}),
costPerTask: readNested({
model,
path: [
'artificial_analysis_intelligence_index_cost',
'cost_per_task',
'total_cost',
],
}),
effort:
typeof model.name === 'string'
? parseArtificialAnalysisEffort(model.name)
: undefined,
aliases,
};
if (informationScore(record) === 0) {
continue;
}
for (const alias of aliases) {
const key = normalizeModelName(alias);
if (key.length === 0) {
continue;
}
// The bare key keeps the ceiling; the effort key lets a pinned variant
// read the figure taken at its own effort.
file(key, record);
if (isDefined(record.effort)) {
file(buildEffortLookupKey(key, record.effort), record);
}
}
}
if (index.size === 0) {
throw new Error(
`${models.length} models returned from ${url} but none carried a measurement`,
);
}
return index;
};