mirror of
https://github.com/anomalyco/models.dev.git
synced 2026-11-23 15:31:39 +08:00
feat: add model type filtering (#7579)
* feat: add model type filtering * fix: preserve model types across catalog paths --------- Co-authored-by: opencode-agent <opencode-agent@users.noreply.github.com>
This commit is contained in:
1 parent
e20b0c573a
commit
6947a51e1b
22 files changed
+589
-52
No files matched your search
@@ -22,6 +22,17 @@ You can access this data through an API.
|
||||
curl https://models.dev/api.json
|
||||
```
|
||||
|
||||
Specialized model types are omitted by default. Filter by one or more
|
||||
comma-separated model types, or use `all` for the complete catalog:
|
||||
|
||||
```bash
|
||||
curl "https://models.dev/api.json?type=decision"
|
||||
curl "https://models.dev/api.json?type=all"
|
||||
```
|
||||
|
||||
The currently supported model type is `decision`. The `type` parameter is also
|
||||
available on `models.json`, `catalog.json`, and `model-schema.json`.
|
||||
|
||||
Use the **Model ID** field to do a lookup on any model; it's the identifier used by [AI SDK](https://ai-sdk.dev/).
|
||||
|
||||
Provider-agnostic model metadata is available separately:
|
||||
@@ -270,6 +281,7 @@ Models must conform to the following schema, as defined in `packages/core/src/sc
|
||||
**Model Schema:**
|
||||
|
||||
- `name`: String — Display name of the model
|
||||
- `type` _(optional)_: String — Specialized model behavior; currently supports `decision`
|
||||
- `attachment`: Boolean — Supports file attachments
|
||||
- `reasoning`: Boolean — Supports reasoning / chain-of-thought
|
||||
- `tool_call`: Boolean - Supports tool calling
|
||||
|
||||
@@ -24,6 +24,9 @@
|
||||
},
|
||||
"packages/function": {
|
||||
"name": "@models.dev/function",
|
||||
"dependencies": {
|
||||
"@models.dev/core": "workspace:*",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "4.20250522.0",
|
||||
"@tsconfig/bun": "catalog:",
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
# - https://typesafe.ai/blog/introducing-system-one-models-and-jev
|
||||
# The 64k context limit covers the state plus all questions in one request.
|
||||
name = "Jev"
|
||||
type = "decision"
|
||||
description = "System One model for fast, typed probabilistic decisions over text or structured state"
|
||||
release_date = "2026-09-15"
|
||||
last_updated = "2026-09-15"
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
export const MODEL_TYPES = ["decision"] as const;
|
||||
|
||||
export type ModelTypeValue = (typeof MODEL_TYPES)[number];
|
||||
export type ModelTypeFilter = "default" | "all" | ModelTypeValue[];
|
||||
|
||||
interface TypedModel {
|
||||
type?: ModelTypeValue;
|
||||
}
|
||||
|
||||
interface TypedProvider {
|
||||
models: Record<string, TypedModel>;
|
||||
}
|
||||
|
||||
export class InvalidModelTypeError extends Error {
|
||||
constructor(value: string) {
|
||||
super(`Invalid type value: ${value}`);
|
||||
this.name = "InvalidModelTypeError";
|
||||
}
|
||||
}
|
||||
|
||||
export function parseModelTypes(value: string | null): ModelTypeFilter {
|
||||
if (value === null || value === "") return "default";
|
||||
if (value === "all") return "all";
|
||||
|
||||
const types = value.split(",");
|
||||
if (
|
||||
types.length === 0 ||
|
||||
types.includes("all") ||
|
||||
types.some((type) => !MODEL_TYPES.includes(type as ModelTypeValue))
|
||||
) {
|
||||
throw new InvalidModelTypeError(value);
|
||||
}
|
||||
|
||||
return [...new Set(types)] as ModelTypeValue[];
|
||||
}
|
||||
|
||||
function includesModel(model: TypedModel, filter: ModelTypeFilter) {
|
||||
if (filter === "all") return true;
|
||||
if (filter === "default") return model.type === undefined;
|
||||
return model.type !== undefined && filter.includes(model.type);
|
||||
}
|
||||
|
||||
export function filterProvidersByModelType<
|
||||
T extends Record<string, TypedProvider>,
|
||||
>(providers: T, filter: ModelTypeFilter): T {
|
||||
if (filter === "all") return providers;
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(providers).flatMap(([providerID, provider]) => {
|
||||
const models = Object.fromEntries(
|
||||
Object.entries(provider.models).filter(([, model]) =>
|
||||
includesModel(model, filter),
|
||||
),
|
||||
);
|
||||
return Object.keys(models).length === 0
|
||||
? []
|
||||
: [[providerID, { ...provider, models }]];
|
||||
}),
|
||||
) as T;
|
||||
}
|
||||
|
||||
export function filterModelsByModelType<T extends Record<string, TypedModel>>(
|
||||
models: T,
|
||||
filter: ModelTypeFilter,
|
||||
): T {
|
||||
if (filter === "all") return models;
|
||||
return Object.fromEntries(
|
||||
Object.entries(models).filter(([, model]) => includesModel(model, filter)),
|
||||
) as T;
|
||||
}
|
||||
|
||||
export function filterCatalogByModelType<
|
||||
TProviders extends Record<string, TypedProvider>,
|
||||
TModels extends Record<string, TypedModel>,
|
||||
>(
|
||||
catalog: { providers: TProviders; models: TModels },
|
||||
filter: ModelTypeFilter,
|
||||
): { providers: TProviders; models: TModels } {
|
||||
return {
|
||||
providers: filterProvidersByModelType(catalog.providers, filter),
|
||||
models: filterModelsByModelType(catalog.models, filter),
|
||||
};
|
||||
}
|
||||
@@ -2,3 +2,4 @@ export * from "./schema.js";
|
||||
export * from "./generate.js";
|
||||
export * from "./describe.js";
|
||||
export * from "./family.js";
|
||||
export * from "./filter.js";
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { ModelFamily } from "./family";
|
||||
import { MODEL_TYPES } from "./filter";
|
||||
|
||||
type JsonValue =
|
||||
| string
|
||||
@@ -148,6 +149,8 @@ const DateString = z
|
||||
|
||||
const Modality = z.enum(["text", "audio", "image", "video", "pdf"]);
|
||||
|
||||
export const ModelType = z.enum(MODEL_TYPES);
|
||||
|
||||
const Modalities = z
|
||||
.object({
|
||||
input: z.array(Modality),
|
||||
@@ -219,6 +222,7 @@ export const BenchmarkResult = z
|
||||
|
||||
const ModelMetadataBase = z.object({
|
||||
id: z.string(),
|
||||
type: ModelType.optional(),
|
||||
name: z.string().min(1, "Model name cannot be empty"),
|
||||
description: z.string().min(1, "Model description cannot be empty"),
|
||||
family: ModelFamily.optional(),
|
||||
@@ -245,6 +249,7 @@ export type ModelMetadata = z.infer<typeof ModelMetadata>;
|
||||
|
||||
const ModelBase = z.object({
|
||||
id: z.string(),
|
||||
type: ModelType.optional(),
|
||||
name: z.string().min(1, "Model name cannot be empty"),
|
||||
description: z.string().min(1, "Model description cannot be empty"),
|
||||
family: ModelFamily.optional(),
|
||||
|
||||
@@ -1011,6 +1011,7 @@ export function formatToml(model: z.infer<typeof SyncedAuthoredModel>) {
|
||||
if ("base_model_omit" in model && model.base_model_omit !== undefined) {
|
||||
lines.push(`base_model_omit = [${model.base_model_omit.map(quote).join(", ")}]`);
|
||||
}
|
||||
if (model.type !== undefined) lines.push(`type = ${quote(model.type)}`);
|
||||
if (model.name !== undefined) lines.push(`name = ${quote(model.name)}`);
|
||||
if (model.description !== undefined) lines.push(`description = ${quote(model.description)}`);
|
||||
if (model.family !== undefined) lines.push(`family = ${quote(model.family)}`);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
|
||||
import {
|
||||
filterCatalogByModelType,
|
||||
generateCatalog,
|
||||
InvalidModelTypeError,
|
||||
parseModelTypes,
|
||||
} from "../src/index.js";
|
||||
import type { ModelMetadata, Provider } from "../src/index.js";
|
||||
import path from "node:path";
|
||||
|
||||
describe("model type filtering", () => {
|
||||
test("defaults to untyped models and supports specific types and all", () => {
|
||||
expect(parseModelTypes(null)).toBe("default");
|
||||
expect(parseModelTypes("")).toBe("default");
|
||||
expect(parseModelTypes("decision")).toEqual(["decision"]);
|
||||
expect(parseModelTypes("all")).toBe("all");
|
||||
});
|
||||
|
||||
test("rejects unknown types and combining all with a type", () => {
|
||||
expect(() => parseModelTypes("unknown")).toThrow(InvalidModelTypeError);
|
||||
expect(() => parseModelTypes("all,decision")).toThrow(
|
||||
InvalidModelTypeError,
|
||||
);
|
||||
});
|
||||
|
||||
test("omits typed models by default", () => {
|
||||
const catalog = fixture();
|
||||
const filtered = filterCatalogByModelType(catalog, "default");
|
||||
|
||||
expect(Object.keys(filtered.models)).toEqual(["standard"]);
|
||||
expect(Object.keys(filtered.providers.example!.models)).toEqual([
|
||||
"standard",
|
||||
]);
|
||||
expect(filtered.providers.decisionOnly).toBeUndefined();
|
||||
});
|
||||
|
||||
test("filters canonical and provider models by requested type", () => {
|
||||
const catalog = fixture();
|
||||
const filtered = filterCatalogByModelType(catalog, ["decision"]);
|
||||
|
||||
expect(Object.keys(filtered.models)).toEqual(["decision"]);
|
||||
expect(Object.keys(filtered.providers.example!.models)).toEqual([
|
||||
"decision",
|
||||
]);
|
||||
expect(Object.keys(filtered.providers.decisionOnly!.models)).toEqual([
|
||||
"decision",
|
||||
]);
|
||||
expect(filterCatalogByModelType(catalog, "all")).toEqual(catalog);
|
||||
});
|
||||
|
||||
test("every repository Jev model inherits decision and is omitted by default", async () => {
|
||||
const root = path.join(import.meta.dir, "..", "..", "..");
|
||||
const catalog = await generateCatalog(root);
|
||||
const jevModels = Object.values(catalog.providers).flatMap((provider) =>
|
||||
Object.values(provider.models).filter((model) =>
|
||||
model.id.toLowerCase().includes("jev"),
|
||||
),
|
||||
);
|
||||
|
||||
expect(jevModels.length).toBeGreaterThan(0);
|
||||
expect(jevModels.every((model) => model.type === "decision")).toBe(true);
|
||||
|
||||
const defaults = filterCatalogByModelType(catalog, "default");
|
||||
expect(
|
||||
Object.values(defaults.providers).some((provider) =>
|
||||
Object.values(provider.models).some((model) => model.type !== undefined),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(defaults.models["typesafe/jev-latest"]).toBeUndefined();
|
||||
expect(defaults.providers.vivgrid?.models.jev).toBeUndefined();
|
||||
|
||||
const decisions = filterCatalogByModelType(catalog, ["decision"]);
|
||||
expect(decisions.models["typesafe/jev-latest"]?.type).toBe("decision");
|
||||
expect(
|
||||
Object.values(decisions.providers).flatMap((provider) =>
|
||||
Object.values(provider.models),
|
||||
).length,
|
||||
).toBe(jevModels.length);
|
||||
});
|
||||
});
|
||||
|
||||
function fixture() {
|
||||
const standard = model("standard-model");
|
||||
const decision = model("decision-model", "decision");
|
||||
return {
|
||||
models: { standard, decision },
|
||||
providers: {
|
||||
example: {
|
||||
id: "example",
|
||||
models: { standard, decision },
|
||||
} as unknown as Provider,
|
||||
decisionOnly: {
|
||||
id: "decision-only",
|
||||
models: { decision },
|
||||
} as unknown as Provider,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function model(id: string, type?: "decision") {
|
||||
return { id, type } as unknown as ModelMetadata;
|
||||
}
|
||||
@@ -70,6 +70,12 @@ describe("model schema", () => {
|
||||
expect(AuthoredModel.safeParse(model).success).toBe(false);
|
||||
});
|
||||
|
||||
test("accepts decision model types", () => {
|
||||
const model = baseModel({ type: "decision" });
|
||||
|
||||
expect(AuthoredModel.safeParse(model).success).toBe(true);
|
||||
});
|
||||
|
||||
test("accepts calendar-valid model dates", () => {
|
||||
for (const field of dateFields) {
|
||||
for (const value of [
|
||||
|
||||
@@ -2806,6 +2806,28 @@ test("resolves Eden AI aliases to the model they point at", () => {
|
||||
).toBe("anthropic/claude-opus-5");
|
||||
});
|
||||
|
||||
test("preserves model type when formatting synced TOML", () => {
|
||||
const content = formatToml({
|
||||
id: "typesafe/jev-latest",
|
||||
type: "decision",
|
||||
name: "Jev",
|
||||
description: "System One model for typed decisions",
|
||||
release_date: "2026-09-15",
|
||||
last_updated: "2026-09-15",
|
||||
attachment: false,
|
||||
reasoning: false,
|
||||
tool_call: false,
|
||||
open_weights: false,
|
||||
limit: { context: 64_000, output: 0 },
|
||||
modalities: { input: ["text"], output: ["text"] },
|
||||
});
|
||||
|
||||
expect(Bun.TOML.parse(content)).toMatchObject({
|
||||
type: "decision",
|
||||
name: "Jev",
|
||||
});
|
||||
});
|
||||
|
||||
test("formats interleaved as a root field before reasoning option tables", () => {
|
||||
const content = formatToml({
|
||||
id: "example/model",
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
"name": "@models.dev/function",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@models.dev/core": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "4.20250522.0",
|
||||
"@tsconfig/bun": "catalog:"
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
import {
|
||||
filterCatalogByModelType,
|
||||
filterModelsByModelType,
|
||||
filterProvidersByModelType,
|
||||
InvalidModelTypeError,
|
||||
MODEL_TYPES,
|
||||
parseModelTypes,
|
||||
} from "@models.dev/core/src/filter.js";
|
||||
import type { ModelTypeValue } from "@models.dev/core/src/filter.js";
|
||||
|
||||
export interface Env {
|
||||
ASSETS: any;
|
||||
PosthogToken: string;
|
||||
@@ -64,11 +74,8 @@ export default {
|
||||
}
|
||||
|
||||
if (url.pathname === "/model-schema.json") {
|
||||
const apiUrl = new URL(url);
|
||||
apiUrl.pathname = "/_api.json";
|
||||
const apiResponse = await env.ASSETS.fetch(
|
||||
new Request(apiUrl.toString(), request),
|
||||
);
|
||||
const apiResponse = await catalogResponse(url, request, env, "api");
|
||||
if (!apiResponse.ok) return apiResponse;
|
||||
const providers = (await apiResponse.json()) as Record<
|
||||
string,
|
||||
{ models: Record<string, unknown> }
|
||||
@@ -102,11 +109,11 @@ export default {
|
||||
}
|
||||
|
||||
if (url.pathname === "/api.json") {
|
||||
url.pathname = "/_api.json";
|
||||
return catalogResponse(url, request, env, "api");
|
||||
} else if (url.pathname === "/models.json") {
|
||||
url.pathname = "/_models.json";
|
||||
return catalogResponse(url, request, env, "models");
|
||||
} else if (url.pathname === "/catalog.json") {
|
||||
url.pathname = "/_catalog.json";
|
||||
return catalogResponse(url, request, env, "catalog");
|
||||
} else if (
|
||||
url.pathname === "/" ||
|
||||
url.pathname === "/index.html" ||
|
||||
@@ -143,6 +150,81 @@ export default {
|
||||
},
|
||||
};
|
||||
|
||||
type CatalogEndpoint = "api" | "models" | "catalog";
|
||||
|
||||
async function catalogResponse(
|
||||
url: URL,
|
||||
request: Request,
|
||||
env: Env,
|
||||
endpoint: CatalogEndpoint,
|
||||
) {
|
||||
let filter;
|
||||
try {
|
||||
filter = parseModelTypes(url.searchParams.get("type"));
|
||||
} catch (error) {
|
||||
if (!(error instanceof InvalidModelTypeError)) throw error;
|
||||
return Response.json(
|
||||
{
|
||||
error: error.message,
|
||||
allowed: [...MODEL_TYPES, "all"],
|
||||
},
|
||||
{
|
||||
status: 400,
|
||||
headers: { "Access-Control-Allow-Origin": "*" },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const assetUrl = new URL(url);
|
||||
const suffix = filter === "default"
|
||||
? ""
|
||||
: filter === "all"
|
||||
? "-all"
|
||||
: filter.length === 1
|
||||
? `-${filter[0]}`
|
||||
: undefined;
|
||||
assetUrl.pathname = `/_${endpoint}${suffix ?? "-all"}.json`;
|
||||
assetUrl.search = "";
|
||||
const assetResponse = await env.ASSETS.fetch(
|
||||
new Request(assetUrl.toString(), request),
|
||||
);
|
||||
if (!assetResponse.ok || suffix !== undefined) return assetResponse;
|
||||
|
||||
const value = await assetResponse.json();
|
||||
const filtered = endpoint === "api"
|
||||
? filterProvidersByModelType(
|
||||
value as Record<string, CatalogProvider>,
|
||||
filter,
|
||||
)
|
||||
: endpoint === "models"
|
||||
? filterModelsByModelType(
|
||||
value as Record<string, CatalogModel>,
|
||||
filter,
|
||||
)
|
||||
: filterCatalogByModelType(
|
||||
value as {
|
||||
providers: Record<string, CatalogProvider>;
|
||||
models: Record<string, CatalogModel>;
|
||||
},
|
||||
filter,
|
||||
);
|
||||
|
||||
const headers = new Headers(assetResponse.headers);
|
||||
headers.delete("Content-Length");
|
||||
headers.delete("ETag");
|
||||
headers.set("Content-Type", "application/json");
|
||||
headers.set("Cache-Control", "public, max-age=3600");
|
||||
return new Response(JSON.stringify(filtered), { headers });
|
||||
}
|
||||
|
||||
interface CatalogModel {
|
||||
type?: ModelTypeValue;
|
||||
}
|
||||
|
||||
interface CatalogProvider {
|
||||
models: Record<string, CatalogModel>;
|
||||
}
|
||||
|
||||
function isHtmlRoute(pathname: string) {
|
||||
return (
|
||||
pathname === "/models" ||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
|
||||
import worker, { type Env } from "../src/worker.js";
|
||||
|
||||
const textModel = {
|
||||
id: "text-model",
|
||||
modalities: { input: ["text"], output: ["text"] },
|
||||
};
|
||||
const decisionModel = {
|
||||
id: "decision-model",
|
||||
type: "decision",
|
||||
modalities: { input: ["text"], output: ["text"] },
|
||||
};
|
||||
const providers = {
|
||||
example: {
|
||||
id: "example",
|
||||
models: { text: textModel, decision: decisionModel },
|
||||
},
|
||||
};
|
||||
const models = { text: textModel, decision: decisionModel };
|
||||
|
||||
describe("catalog API model type filtering", () => {
|
||||
test("omits typed models from api.json by default", async () => {
|
||||
const response = await request("/api.json");
|
||||
const body = await response.json();
|
||||
|
||||
expect(Object.keys(body.example.models)).toEqual(["text"]);
|
||||
});
|
||||
|
||||
test("omits typed models from models.json by default", async () => {
|
||||
const response = await request("/models.json");
|
||||
const body = await response.json();
|
||||
|
||||
expect(Object.keys(body)).toEqual(["text"]);
|
||||
});
|
||||
|
||||
test("omits typed models from catalog.json by default", async () => {
|
||||
const response = await request("/catalog.json");
|
||||
const body = await response.json();
|
||||
|
||||
expect(Object.keys(body.models)).toEqual(["text"]);
|
||||
expect(Object.keys(body.providers.example.models)).toEqual(["text"]);
|
||||
});
|
||||
|
||||
test("returns explicitly requested decision models", async () => {
|
||||
const response = await request("/catalog.json?type=decision");
|
||||
const body = await response.json();
|
||||
|
||||
expect(Object.keys(body.models)).toEqual(["decision"]);
|
||||
expect(Object.keys(body.providers.example.models)).toEqual(["decision"]);
|
||||
});
|
||||
|
||||
test("returns the complete static catalog for all", async () => {
|
||||
const response = await request("/models.json?type=all");
|
||||
const body = await response.json();
|
||||
|
||||
expect(Object.keys(body)).toEqual(["text", "decision"]);
|
||||
});
|
||||
|
||||
test("omits typed models from model-schema.json by default", async () => {
|
||||
const response = await request("/model-schema.json");
|
||||
const body = await response.json();
|
||||
|
||||
expect(body.$defs.Model.enum).toEqual(["example/text"]);
|
||||
});
|
||||
|
||||
test("includes typed models in model-schema.json when requested", async () => {
|
||||
const response = await request("/model-schema.json?type=all");
|
||||
const body = await response.json();
|
||||
|
||||
expect(body.$defs.Model.enum).toEqual([
|
||||
"example/decision",
|
||||
"example/text",
|
||||
]);
|
||||
});
|
||||
|
||||
test("rejects unknown model types", async () => {
|
||||
const response = await request("/api.json?type=unknown");
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
async function request(path: string) {
|
||||
const env = {
|
||||
ASSETS: {
|
||||
fetch(input: Request) {
|
||||
const pathname = new URL(input.url).pathname;
|
||||
if (pathname === "/_api.json") {
|
||||
return Response.json({
|
||||
example: { ...providers.example, models: { text: textModel } },
|
||||
});
|
||||
}
|
||||
if (pathname === "/_api-all.json") return Response.json(providers);
|
||||
if (pathname === "/_api-decision.json") {
|
||||
return Response.json({
|
||||
example: { ...providers.example, models: { decision: decisionModel } },
|
||||
});
|
||||
}
|
||||
if (pathname === "/_models.json") {
|
||||
return Response.json({ text: textModel });
|
||||
}
|
||||
if (pathname === "/_models-all.json") return Response.json(models);
|
||||
if (pathname === "/_models-decision.json") {
|
||||
return Response.json({ decision: decisionModel });
|
||||
}
|
||||
if (pathname === "/_catalog.json") {
|
||||
return Response.json({
|
||||
providers: {
|
||||
example: { ...providers.example, models: { text: textModel } },
|
||||
},
|
||||
models: { text: textModel },
|
||||
});
|
||||
}
|
||||
if (pathname === "/_catalog-all.json") {
|
||||
return Response.json({ providers, models });
|
||||
}
|
||||
if (pathname === "/_catalog-decision.json") {
|
||||
return Response.json({
|
||||
providers: {
|
||||
example: { ...providers.example, models: { decision: decisionModel } },
|
||||
},
|
||||
models: { decision: decisionModel },
|
||||
});
|
||||
}
|
||||
return new Response(null, { status: 404 });
|
||||
},
|
||||
},
|
||||
} as unknown as Env;
|
||||
|
||||
return worker.fetch(
|
||||
new Request(`https://models.dev${path}`, {
|
||||
headers: { "user-agent": "test" },
|
||||
}),
|
||||
env,
|
||||
{ waitUntil() {} } as unknown as ExecutionContext,
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ModelsDevError } from "./error.js"
|
||||
import type { Catalog, ModelMetadataMap, ProviderMap } from "./types.js"
|
||||
import type { Catalog, ModelMetadataMap, ModelType, ProviderMap } from "./types.js"
|
||||
|
||||
/** Accepted anywhere headers can be passed. Same shapes as the standard `HeadersInit`. */
|
||||
export type HeadersInput = Headers | Record<string, string> | Array<[string, string]>
|
||||
@@ -21,6 +21,8 @@ export interface RequestOptions {
|
||||
readonly signal?: AbortSignal
|
||||
/** Extra headers for this request. Overrides client-level headers. */
|
||||
readonly headers?: HeadersInput
|
||||
/** Specialized model types to include. Omit for standard models; use `"all"` for the complete catalog. */
|
||||
readonly modelTypes?: "all" | readonly ModelType[]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -41,7 +43,15 @@ export function make(options: ClientOptions = {}) {
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(new URL(path, base), {
|
||||
const url = new URL(path, base)
|
||||
const modelTypes = requestOptions?.modelTypes
|
||||
if (modelTypes === "all") {
|
||||
url.searchParams.set("type", "all")
|
||||
} else if (modelTypes && modelTypes.length > 0) {
|
||||
url.searchParams.set("type", modelTypes.join(","))
|
||||
}
|
||||
|
||||
response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers,
|
||||
signal: requestOptions?.signal,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Effect-native client. Requires the optional peer dependency `effect`.
|
||||
export * as Models from "./effect/client.js"
|
||||
export { ModelsDevError, type ClientOptions, type ModelsClient } from "./effect/client.js"
|
||||
export { ModelsDevError, type ClientOptions, type ModelsClient, type RequestOptions } from "./effect/client.js"
|
||||
export type * from "./types.js"
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Context, Effect, Layer, Schema } from "effect"
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http"
|
||||
import type { Catalog, ModelMetadataMap, ProviderMap } from "../types.js"
|
||||
import type { Catalog, ModelMetadataMap, ModelType, ProviderMap } from "../types.js"
|
||||
|
||||
/** The only error in the failure channel of client methods. Wraps the underlying `HttpClientError` as `cause`. */
|
||||
export class ModelsDevError extends Schema.TaggedErrorClass<ModelsDevError>()("ModelsDevError", {
|
||||
@@ -14,6 +14,11 @@ export interface ClientOptions {
|
||||
readonly headers?: Record<string, string>
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
/** Specialized model types to include. Omit for standard models; use `"all"` for the complete catalog. */
|
||||
readonly modelTypes?: "all" | readonly ModelType[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a stateless models.dev client on top of the `HttpClient` service
|
||||
* from the environment (`FetchHttpClient.layer`, `NodeHttpClient.layer`, or a
|
||||
@@ -26,9 +31,17 @@ export const make = (options?: ClientOptions) =>
|
||||
const baseUrl = options?.baseUrl ?? "https://models.dev"
|
||||
const base = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/"
|
||||
|
||||
const get = <A>(path: string): Effect.Effect<A, ModelsDevError> =>
|
||||
http
|
||||
.get(new URL(path, base), {
|
||||
const get = <A>(path: string, requestOptions?: RequestOptions): Effect.Effect<A, ModelsDevError> => {
|
||||
const url = new URL(path, base)
|
||||
const modelTypes = requestOptions?.modelTypes
|
||||
if (modelTypes === "all") {
|
||||
url.searchParams.set("type", "all")
|
||||
} else if (modelTypes && modelTypes.length > 0) {
|
||||
url.searchParams.set("type", modelTypes.join(","))
|
||||
}
|
||||
|
||||
return http
|
||||
.get(url, {
|
||||
headers: options?.headers,
|
||||
})
|
||||
.pipe(
|
||||
@@ -37,14 +50,15 @@ export const make = (options?: ClientOptions) =>
|
||||
Effect.map((data) => data as A),
|
||||
Effect.mapError((cause) => new ModelsDevError({ cause })),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
/** All providers with their models, pricing, and limits (`/api.json`). */
|
||||
providers: () => get<ProviderMap>("api.json"),
|
||||
providers: (options?: RequestOptions) => get<ProviderMap>("api.json", options),
|
||||
/** Provider-agnostic model metadata (`/models.json`). */
|
||||
models: () => get<ModelMetadataMap>("models.json"),
|
||||
models: (options?: RequestOptions) => get<ModelMetadataMap>("models.json", options),
|
||||
/** Providers and model metadata in a single request (`/catalog.json`). */
|
||||
catalog: () => get<Catalog>("catalog.json"),
|
||||
catalog: (options?: RequestOptions) => get<Catalog>("catalog.json", options),
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -80,6 +80,9 @@ export interface ModelCost extends Cost {
|
||||
/** Input/output data types a model supports. */
|
||||
export type Modality = "text" | "audio" | "image" | "video" | "pdf"
|
||||
|
||||
/** A model's specialized behavioral contract. Omitted for standard generative models. */
|
||||
export type ModelType = "decision"
|
||||
|
||||
export interface Modalities {
|
||||
input: Modality[]
|
||||
output: Modality[]
|
||||
@@ -143,6 +146,7 @@ export interface BenchmarkResult {
|
||||
export interface ModelMetadata {
|
||||
/** Canonical model ID, e.g. "anthropic/claude-opus-4-6". */
|
||||
id: string
|
||||
type?: ModelType
|
||||
name: string
|
||||
description: string
|
||||
family?: ModelFamily
|
||||
@@ -208,6 +212,7 @@ export interface ModelProviderConfig {
|
||||
export interface Model {
|
||||
/** Provider-scoped model ID, e.g. "claude-opus-4-6". */
|
||||
id: string
|
||||
type?: ModelType
|
||||
name: string
|
||||
description: string
|
||||
family?: ModelFamily
|
||||
|
||||
@@ -40,6 +40,17 @@ test("models() and catalog() hit their endpoints", async () => {
|
||||
expect(calls.map((call) => call.url.href)).toEqual(["https://models.dev/models.json", "https://models.dev/catalog.json"])
|
||||
})
|
||||
|
||||
test("catalog endpoints encode model type filters", async () => {
|
||||
const { calls, fetch } = stub({})
|
||||
const client = Models.make({ fetch })
|
||||
await client.providers({ modelTypes: ["decision"] })
|
||||
await client.models({ modelTypes: "all" })
|
||||
expect(calls.map((call) => call.url.href)).toEqual([
|
||||
"https://models.dev/api.json?type=decision",
|
||||
"https://models.dev/models.json?type=all",
|
||||
])
|
||||
})
|
||||
|
||||
test("baseUrl with subpath is preserved, with or without trailing slash", async () => {
|
||||
const { calls, fetch } = stub({})
|
||||
await Models.make({ fetch, baseUrl: "https://example.com/mirror" }).providers()
|
||||
|
||||
@@ -42,6 +42,20 @@ test("models() and catalog() hit their endpoints, baseUrl subpath preserved", as
|
||||
])
|
||||
})
|
||||
|
||||
test("catalog endpoints encode model type filters", async () => {
|
||||
const { requests, layer } = stub({})
|
||||
const program = Effect.gen(function* () {
|
||||
const client = yield* Models.make()
|
||||
yield* client.providers({ modelTypes: ["decision"] })
|
||||
yield* client.catalog({ modelTypes: "all" })
|
||||
})
|
||||
await program.pipe(Effect.provide(layer), Effect.runPromise)
|
||||
expect(requests.map((request) => request.url)).toEqual([
|
||||
"https://models.dev/api.json?type=decision",
|
||||
"https://models.dev/catalog.json?type=all",
|
||||
])
|
||||
})
|
||||
|
||||
test("custom headers are sent", async () => {
|
||||
const { requests, layer } = stub({})
|
||||
const program = Effect.gen(function* () {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { RenderedPages, Providers, Models, renderDocument } from "../src/render";
|
||||
import {
|
||||
filterCatalogByModelType,
|
||||
MODEL_TYPES,
|
||||
type ModelTypeFilter,
|
||||
} from "@models.dev/core";
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
|
||||
@@ -74,15 +79,18 @@ for (const [route, rendered] of RenderedPages) {
|
||||
await Bun.write(filePath, renderDocument(template, rendered));
|
||||
}
|
||||
|
||||
await Bun.write("./dist/api.json", JSON.stringify(Providers));
|
||||
await Bun.write(
|
||||
"./dist/catalog.json",
|
||||
JSON.stringify({ models: Models, providers: Providers }),
|
||||
);
|
||||
await Bun.write("./dist/models.json", JSON.stringify(Models));
|
||||
const catalog = { models: Models, providers: Providers };
|
||||
const variants: Array<[suffix: string, filter: ModelTypeFilter]> = [
|
||||
["", "default"],
|
||||
["-all", "all"],
|
||||
...MODEL_TYPES.map((type) => [`-${type}`, [type]] as const),
|
||||
];
|
||||
|
||||
await fs.rename("./dist/api.json", "./dist/_api.json");
|
||||
await fs.rename("./dist/catalog.json", "./dist/_catalog.json");
|
||||
await fs.rename("./dist/models.json", "./dist/_models.json");
|
||||
for (const [suffix, filter] of variants) {
|
||||
const filtered = filterCatalogByModelType(catalog, filter);
|
||||
await Bun.write(`./dist/_api${suffix}.json`, JSON.stringify(filtered.providers));
|
||||
await Bun.write(`./dist/_models${suffix}.json`, JSON.stringify(filtered.models));
|
||||
await Bun.write(`./dist/_catalog${suffix}.json`, JSON.stringify(filtered));
|
||||
}
|
||||
|
||||
await fs.rm("./dist/index.html", { force: true });
|
||||
@@ -1497,21 +1497,22 @@ function HelpDialog() {
|
||||
<h2>API</h2>
|
||||
<p>
|
||||
You can access provider data, provider-agnostic model metadata, or the
|
||||
combined catalog through JSON endpoints.
|
||||
combined catalog through JSON endpoints. Specialized model types are
|
||||
omitted by default; the site includes all model types.
|
||||
</p>
|
||||
<div class="code-block">
|
||||
<code>
|
||||
curl <a href="/api.json">https://models.dev/api.json</a>
|
||||
curl <a href="/api.json?type=all">https://models.dev/api.json?type=all</a>
|
||||
</code>
|
||||
</div>
|
||||
<div class="code-block">
|
||||
<code>
|
||||
curl <a href="/models.json">https://models.dev/models.json</a>
|
||||
curl <a href="/models.json?type=all">https://models.dev/models.json?type=all</a>
|
||||
</code>
|
||||
</div>
|
||||
<div class="code-block">
|
||||
<code>
|
||||
curl <a href="/catalog.json">https://models.dev/catalog.json</a>
|
||||
curl <a href="/catalog.json?type=all">https://models.dev/catalog.json?type=all</a>
|
||||
</code>
|
||||
</div>
|
||||
<h2>Logos</h2>
|
||||
|
||||
+35
-21
@@ -1,5 +1,12 @@
|
||||
import Index from "../index.html";
|
||||
import { getRenderedPage, Models, Providers, renderDocument } from "./render";
|
||||
import {
|
||||
filterCatalogByModelType,
|
||||
filterModelsByModelType,
|
||||
filterProvidersByModelType,
|
||||
InvalidModelTypeError,
|
||||
parseModelTypes,
|
||||
} from "@models.dev/core";
|
||||
import path from "path";
|
||||
|
||||
const assetPort = Number(Bun.env.ASSET_PORT ?? 16000);
|
||||
@@ -99,30 +106,37 @@ Bun.serve({
|
||||
},
|
||||
});
|
||||
},
|
||||
"/api.json": () =>
|
||||
Response.json(Providers, {
|
||||
headers: {
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
}),
|
||||
"/models.json": () =>
|
||||
Response.json(Models, {
|
||||
headers: {
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
}),
|
||||
"/catalog.json": () =>
|
||||
Response.json(
|
||||
{ models: Models, providers: Providers },
|
||||
{
|
||||
headers: {
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
},
|
||||
),
|
||||
"/api.json": (req) => catalogResponse(req, "api"),
|
||||
"/models.json": (req) => catalogResponse(req, "models"),
|
||||
"/catalog.json": (req) => catalogResponse(req, "catalog"),
|
||||
},
|
||||
});
|
||||
|
||||
function catalogResponse(req: Request, endpoint: "api" | "models" | "catalog") {
|
||||
let filter;
|
||||
try {
|
||||
filter = parseModelTypes(new URL(req.url).searchParams.get("type"));
|
||||
} catch (error) {
|
||||
if (!(error instanceof InvalidModelTypeError)) throw error;
|
||||
return Response.json({ error: error.message }, { status: 400 });
|
||||
}
|
||||
|
||||
const value = endpoint === "api"
|
||||
? filterProvidersByModelType(Providers, filter)
|
||||
: endpoint === "models"
|
||||
? filterModelsByModelType(Models, filter)
|
||||
: filterCatalogByModelType(
|
||||
{ models: Models, providers: Providers },
|
||||
filter,
|
||||
);
|
||||
|
||||
return Response.json(value, {
|
||||
headers: {
|
||||
"Cache-Control": "public, max-age=3600",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const server = Bun.serve({
|
||||
development: true,
|
||||
hostname: "0.0.0.0",
|
||||
|
||||
Reference in new issue
Block a user