diff --git a/README.md b/README.md index 410385a16..b2ea40280 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,33 @@ You can access this data through an API. curl https://models.dev/api.json ``` +### Query Parameters + +| Parameter | Description | Default | +|-----------|-------------|---------| +| `provider` | Filter to a specific provider's models only | All providers | +| `flatten` | Return models as a flat array with `id` field included | `false` | + +### Examples + +Get all providers and models: + +```bash +curl https://models.dev/api.json +``` + +Get models for a specific provider: + +```bash +curl "https://models.dev/api.json?provider=anthropic" +``` + +Get models for a specific provider as a flat array: + +```bash +curl "https://models.dev/api.json?provider=anthropic&flatten=true" +``` + Use the **Model ID** field to do a lookup on any model; it's the identifier used by [AI SDK](https://ai-sdk.dev/). ### Logos diff --git a/packages/function/src/worker.ts b/packages/function/src/worker.ts index beb8477b7..9e75c5962 100644 --- a/packages/function/src/worker.ts +++ b/packages/function/src/worker.ts @@ -75,6 +75,49 @@ export default { if (url.pathname === "/api.json") { url.pathname = "/_api.json"; + const providerParam = url.searchParams.get("provider"); + const flattenParam = url.searchParams.get("flatten"); + + if (providerParam) { + const apiResponse = await env.ASSETS.fetch( + new Request(url.toString(), request), + ); + const providers = (await apiResponse.json()) as Record< + string, + { models: Record } + >; + + if (providers[providerParam]) { + const models = providers[providerParam].models; + + if (flattenParam === "true") { + const flattened = Object.entries(models).map( + ([id, model]) => ({ id, ...model as object }), + ); + return new Response(JSON.stringify(flattened), { + headers: { + "Content-Type": "application/json", + "Cache-Control": "public, max-age=3600", + }, + }); + } + + return new Response(JSON.stringify(models), { + headers: { + "Content-Type": "application/json", + "Cache-Control": "public, max-age=3600", + }, + }); + } + + return new Response( + JSON.stringify({ error: `Provider '${providerParam}' not found` }), + { + status: 404, + headers: { "Content-Type": "application/json" }, + }, + ); + } } else if ( url.pathname === "/" || url.pathname === "/index.html" ||