/* Model registry. Built-in providers follow Pi's table (base URL, API and key
* variable); OpenAI-compatible dialects are detected from provider and base
* URL as Pi's detectCompat does; the user's models file adds providers (a
* local server, say) and models, and overrides any field. JSON is read with
* SQLite's JSON functions on a private in-memory connection. */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "models.h"
#include "catalog.h"
#include "cred.h"
#include "endpoints.h"
#include "input.h"
#include "sqlite3.h"
#define API_MESSAGES "anthropic-messages"
#define API_CHAT "openai-completions"
#define API_RESPONSES "openai-responses"
#define API_GEMINI "google-generative-ai"
typedef struct {
const char *name, *base_url, *key_env;
const char *api; /* Pi's wire API name */
} provider_def;
static const provider_def providers[] = {
{"anthropic", "https://api.anthropic.com", "ANTHROPIC_API_KEY", API_MESSAGES},
{"openai", "https://api.openai.com/v1", "OPENAI_API_KEY", API_RESPONSES},
{"openrouter", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY", API_CHAT},
{"xai", "https://api.x.ai/v1", "XAI_API_KEY", API_RESPONSES},
{"groq", "https://api.groq.com/openai/v1", "GROQ_API_KEY", API_CHAT},
{"cerebras", "https://api.cerebras.ai/v1", "CEREBRAS_API_KEY", API_CHAT},
{"deepseek", "https://api.deepseek.com", "DEEPSEEK_API_KEY", API_CHAT},
{"together", "https://api.together.ai/v1", "TOGETHER_API_KEY", API_CHAT},
{"fireworks", "https://api.fireworks.ai/inference/v1", "FIREWORKS_API_KEY", API_CHAT},
{"huggingface", "https://router.huggingface.co/v1", "HF_TOKEN", API_CHAT},
{"nvidia", "https://integrate.api.nvidia.com/v1", "NVIDIA_API_KEY", API_CHAT},
{"moonshotai", "https://api.moonshot.ai/v1", "MOONSHOT_API_KEY", API_CHAT},
{"zai", "https://api.z.ai/api/coding/paas/v4", "ZAI_API_KEY", API_CHAT},
{"google", "https://generativelanguage.googleapis.com/v1beta", "GEMINI_API_KEY", API_GEMINI},
};
/* Models whose limits pic knows; everything else takes Pi's defaults
* (128000 context, 16384 output) unless the models file says otherwise. */
static const struct {
const char *provider, *id;
long context_window, max_tokens;
int reasoning;
} known_models[] = {
{"anthropic", "claude-fable-5-2", 1000000, 128000, 1}, {"anthropic", "claude-opus-5-5", 1000000, 128000, 1},
{"anthropic", "claude-opus-5", 1000000, 128000, 1}, {"anthropic", "claude-sonnet-5-5", 1000000, 128000, 1},
{"anthropic", "claude-sonnet-5", 1000000, 128000, 1}, {"anthropic", "claude-haiku-5-5", 1000000, 128000, 1},
{"anthropic", "claude-haiku-4-5", 200000, 64000, 1},
{"google", "gemini-3.1-pro-preview", 1048576, 65536, 1}, {"google", "gemini-3-flash-preview", 1048576, 65536, 1},
{"google", "gemini-2.5-pro", 1048576, 65536, 1}, {"google", "gemini-2.5-flash", 1048576, 65536, 1},
{"google", "gemini-2.5-flash-lite", 1048576, 65536, 1},
};
static void copy(char *dst, size_t cap, const char *src) { (void)snprintf(dst, cap, "%s", src ? src : ""); }
/* Whether S names a wire API pic has an adapter for. */
static int api_known(const char *s) {
return strcmp(s, API_MESSAGES) == 0 || strcmp(s, API_CHAT) == 0 || strcmp(s, API_RESPONSES) == 0 ||
strcmp(s, API_GEMINI) == 0;
}
static int api_is(const pic_model *m, const char *api) { return strcmp(m->api, api) == 0; }
void pic_model_url(const pic_model *m, char *out, size_t cap) {
if (api_is(m, API_GEMINI)) {
(void)snprintf(out, cap, "%s/models/%s:streamGenerateContent?alt=sse", m->base_url, m->id);
return;
}
(void)snprintf(out, cap, "%s%s", m->base_url,
api_is(m, API_MESSAGES) ? "/v1/messages" : api_is(m, API_CHAT) ? "/chat/completions" : "/responses");
}
/* Pi's detectCompat for openai-completions, by provider name or base URL. */
static void detect_compat(pic_model *m) {
const char *p = m->provider, *u = m->base_url;
#define IS(name, host) (strcmp(p, name) == 0 || strstr(u, host) != NULL)
int openrouter = IS("openrouter", "openrouter.ai"), deepseek = IS("deepseek", "deepseek.com"),
zai = IS("zai", "api.z.ai") || strstr(u, "open.bigmodel.cn") != NULL, moonshot = IS("moonshotai", "api.moonshot."),
together = IS("together", "api.together.ai") || strstr(u, "api.together.xyz") != NULL,
cerebras = IS("cerebras", "cerebras.ai"), nvidia = IS("nvidia", "integrate.api.nvidia.com"),
grok = IS("xai", "api.x.ai");
#undef IS
int nonstandard = nvidia || cerebras || grok || together || deepseek || zai || moonshot || strstr(u, "chutes.ai");
pic_compat *c = &m->compat;
memset(c, 0, sizeof *c);
c->supports_store = !nonstandard;
c->supports_developer_role =
(openrouter && (strncmp(m->id, "anthropic/", 10) == 0 || strncmp(m->id, "openai/", 7) == 0)) ||
(!nonstandard && !openrouter);
c->supports_usage_in_streaming = 1;
c->supports_reasoning_effort = !(grok || zai || moonshot || together || nvidia);
c->max_tokens_field_legacy = deepseek || moonshot || together || nvidia || zai || strstr(u, "chutes.ai") != NULL;
c->requires_reasoning_content = deepseek;
c->supports_long_cache = !(together || nvidia);
c->cache_control = openrouter && strncmp(m->id, "anthropic/", 10) == 0;
copy(c->thinking_format, sizeof c->thinking_format,
deepseek ? "deepseek" : zai ? "zai" : together ? "together" : openrouter ? "openrouter" : "openai");
}
/* ---- the user's models file -------------------------------------------- */
static char *read_file(const char *path) {
size_t len;
return pic_input_read(path, 1u << 22, 0, &len, NULL);
}
/* ~/.pic/models.json, else Pi's ~/.pi/agent/models.json, else NULL. */
static char *user_models(char *path, size_t cap) {
const char *home = getenv("HOME"), *override = getenv("PIC_MODELS_FILE");
char *text;
if (override && *override) {
copy(path, cap, override);
return read_file(path);
}
if (!home) {
return NULL;
}
(void)snprintf(path, cap, "%s/.pic/models.json", home);
if ((text = read_file(path))) {
return text;
}
(void)snprintf(path, cap, "%s/.pi/agent/models.json", home);
return read_file(path);
}
static char *sql_text(sqlite3 *db, const char *sql, const char *a, const char *b, const char *c) {
sqlite3_stmt *q = NULL;
char *out = NULL;
const char *args[3] = {a, b, c};
if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) != SQLITE_OK) {
return NULL;
}
for (int i = 0; i < 3 && i < sqlite3_bind_parameter_count(q); i++) {
sqlite3_bind_text(q, i + 1, args[i], -1, SQLITE_STATIC);
}
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
const char *t = (const char *)sqlite3_column_text(q, 0);
out = malloc(strlen(t) + 1);
if (out) {
memcpy(out, t, strlen(t) + 1);
}
}
sqlite3_finalize(q);
return out;
}
/* A string field of a JSON object, or NULL. */
static char *field(sqlite3 *db, const char *obj, const char *path) {
return obj ? sql_text(db, "SELECT CASE json_type(?1, ?2) WHEN 'text' THEN json_extract(?1, ?2) END", obj, path, NULL)
: NULL;
}
/* An integer or boolean field: 1 found (value in *v), 0 absent. */
static int number(sqlite3 *db, const char *obj, const char *path, long *v) {
char *t = obj ? sql_text(db,
"SELECT CASE json_type(?1, ?2) WHEN 'integer' THEN json_extract(?1, ?2)"
" WHEN 'real' THEN CAST(json_extract(?1, ?2) AS INTEGER) WHEN 'true' THEN 1"
" WHEN 'false' THEN 0 END",
obj, path, NULL)
: NULL;
if (!t) {
return 0;
}
*v = strtol(t, NULL, 10);
free(t);
return 1;
}
static void apply_compat(sqlite3 *db, const char *compat, pic_compat *c) {
long v;
char *s;
if (!compat) {
return;
}
if (number(db, compat, "$.supportsStore", &v)) {
c->supports_store = (int)v;
}
if (number(db, compat, "$.supportsDeveloperRole", &v)) {
c->supports_developer_role = (int)v;
}
if (number(db, compat, "$.supportsUsageInStreaming", &v)) {
c->supports_usage_in_streaming = (int)v;
}
if (number(db, compat, "$.supportsLongCacheRetention", &v)) {
c->supports_long_cache = (int)v;
}
if (number(db, compat, "$.supportsReasoningEffort", &v)) {
c->supports_reasoning_effort = (int)v;
}
if (number(db, compat, "$.requiresReasoningContentOnAssistantMessages", &v)) {
c->requires_reasoning_content = (int)v;
}
if (number(db, compat, "$.forceAdaptiveThinking", &v)) {
c->force_adaptive_thinking = (int)v;
}
if ((s = field(db, compat, "$.maxTokensField"))) {
c->max_tokens_field_legacy = strcmp(s, "max_tokens") == 0;
free(s);
}
if ((s = field(db, compat, "$.thinkingFormat"))) {
copy(c->thinking_format, sizeof c->thinking_format, s);
free(s);
}
}
/* Lays an object's thinkingLevelMap over the model's, level by level. */
static void apply_thinking_map(sqlite3 *db, const char *obj, pic_model *m) {
sqlite3_stmt *q = NULL;
if (!obj || sqlite3_prepare_v2(db, "SELECT key, type, value FROM json_each(?1, '$.thinkingLevelMap')"
" WHERE json_valid(?1) AND json_type(?1, '$.thinkingLevelMap') = 'object'",
-1, &q, NULL) != SQLITE_OK) {
return;
}
sqlite3_bind_text(q, 1, obj, -1, SQLITE_STATIC);
while (sqlite3_step(q) == SQLITE_ROW) {
int i = pic_thinking_index((const char *)sqlite3_column_text(q, 0));
const char *type = (const char *)sqlite3_column_text(q, 1);
if (i < 0) {
continue;
}
if (strcmp(type, "null") == 0) {
m->thinking_map.state[i] = 1;
} else if (strcmp(type, "text") == 0) {
m->thinking_map.state[i] = 2;
copy(m->thinking_map.value[i], sizeof m->thinking_map.value[i], (const char *)sqlite3_column_text(q, 2));
}
}
sqlite3_finalize(q);
}
void pic_model_thinking_json(const char *model_json, char *out, size_t cap) {
pic_model m;
sqlite3 *db = NULL;
const char *levels[PIC_THINKING_LEVELS];
long v;
size_t used = 0;
int n;
memset(&m, 0, sizeof m);
if (sqlite3_open(":memory:", &db) == SQLITE_OK) {
m.reasoning = number(db, model_json, "$.reasoning", &v) && v;
apply_thinking_map(db, model_json, &m);
}
sqlite3_close(db);
n = pic_model_thinking_levels(&m, levels);
used += (size_t)snprintf(out, cap, "[");
for (int i = 0; i < n && used < cap; i++) {
used += (size_t)snprintf(out + used, cap - used, "%s\"%s\"", i ? "," : "", levels[i]);
}
if (used < cap) {
(void)snprintf(out + used, cap - used, "]");
}
}
/* "$NAME" names a variable; anything else is the key itself (Pi's rules,
* without "!command", which pic does not run). */
static int apply_key(const char *spec, pic_model *m, char *err, size_t errcap) {
m->key_env[0] = m->key_literal[0] = '\0';
if (spec[0] == '!') {
(void)snprintf(err, errcap, "models file: apiKey commands (\"!…\") are not supported; use \"$VARIABLE\"");
return -1;
}
if (spec[0] == '$') {
copy(m->key_env, sizeof m->key_env, spec + 1);
} else {
copy(m->key_literal, sizeof m->key_literal, spec);
}
return 0;
}
/* Headers object to "Name: value" lines; "$VAR" values read the variable. */
static void apply_headers(sqlite3 *db, const char *headers, pic_model *m) {
sqlite3_stmt *q = NULL;
size_t used = strlen(m->headers);
if (!headers || sqlite3_prepare_v2(db, "SELECT key, value FROM json_each(?) WHERE type='text'", -1, &q, NULL) != SQLITE_OK) {
return;
}
sqlite3_bind_text(q, 1, headers, -1, SQLITE_STATIC);
while (sqlite3_step(q) == SQLITE_ROW) {
const char *k = (const char *)sqlite3_column_text(q, 0), *v = (const char *)sqlite3_column_text(q, 1);
int n;
if (v[0] == '$') {
v = getenv(v + 1) ? getenv(v + 1) : "";
}
n = snprintf(m->headers + used, sizeof m->headers - used, "%s%s: %s", used ? "\n" : "", k, v);
if (n < 0 || (size_t)n >= sizeof m->headers - used) {
break;
}
used += (size_t)n;
}
sqlite3_finalize(q);
}
/* ---- prices and cost ---------------------------------------------------- */
/* A numeric field: 1 found (value in *v), 0 absent or not a number. */
static int real(sqlite3 *db, const char *obj, const char *path, double *v) {
char *t = obj ? sql_text(db, "SELECT CASE WHEN json_type(?1, ?2) IN ('integer','real') THEN json_extract(?1, ?2) END", obj,
path, NULL)
: NULL;
if (!t) {
return 0;
}
*v = strtod(t, NULL);
free(t);
return 1;
}
static void read_rates(sqlite3 *db, const char *obj, const char *prefix, pic_rates *r) {
static const char *const names[4] = {"input", "output", "cacheRead", "cacheWrite"};
double *dst[4] = {&r->input, &r->output, &r->cache_read, &r->cache_write};
char path[96];
for (int i = 0; i < 4; i++) {
(void)snprintf(path, sizeof path, "%s.%s", prefix, names[i]);
*dst[i] = 0;
(void)real(db, obj, path, dst[i]);
}
}
/* Replaces the model's price with OBJ's "cost" object, if it has one. */
static void apply_price(sqlite3 *db, const char *obj, pic_price *p) {
sqlite3_stmt *q = NULL;
if (!obj || !sql_text(db, "SELECT 1 WHERE json_type(?1, '$.cost') = 'object'", obj, NULL, NULL)) {
return;
}
memset(p, 0, sizeof *p);
read_rates(db, obj, "$.cost", &p->base);
if (sqlite3_prepare_v2(db, "SELECT key FROM json_each(?1, '$.cost.tiers') WHERE json_valid(?1)", -1, &q, NULL) != SQLITE_OK) {
return;
}
sqlite3_bind_text(q, 1, obj, -1, SQLITE_STATIC);
while (p->ntiers < PIC_COST_TIERS && sqlite3_step(q) == SQLITE_ROW) {
char path[64];
double above;
(void)snprintf(path, sizeof path, "$.cost.tiers[%d].inputTokensAbove", sqlite3_column_int(q, 0));
if (real(db, obj, path, &above)) {
(void)snprintf(path, sizeof path, "$.cost.tiers[%d]", sqlite3_column_int(q, 0));
p->tier[p->ntiers].above = above;
read_rates(db, obj, path, &p->tier[p->ntiers].rates);
p->ntiers++;
}
}
sqlite3_finalize(q);
}
void pic_cost_calc(const pic_price *price, const pic_tokens *t, pic_cost *out) {
double request = t->input + t->cache_read + t->cache_write, matched = -1, short_write = t->cache_write - t->cache_write_1h;
pic_rates r = price->base;
for (int i = 0; i < price->ntiers; i++) {
if (request > price->tier[i].above && price->tier[i].above > matched) {
r = price->tier[i].rates;
matched = price->tier[i].above;
}
}
out->input = r.input / 1000000 * t->input;
out->output = r.output / 1000000 * t->output;
out->cache_read = r.cache_read / 1000000 * t->cache_read;
out->cache_write = (r.cache_write * short_write + r.input * 2 * t->cache_write_1h) / 1000000;
out->total = out->input + out->output + out->cache_read + out->cache_write;
out->total_from_provider = 0;
}
static double positive(double v) {
return v > 0 ? v : 0;
}
/* A valid billed amount: a finite number, not negative. */
static int valid_cost(sqlite3_stmt *q, int col) {
int type = sqlite3_column_type(q, col);
double v = sqlite3_column_double(q, col);
return (type == SQLITE_INTEGER || type == SQLITE_FLOAT) && isfinite(v) && v >= 0;
}
int pic_usage_cost(const pic_model *m, const char *raw_usage, pic_cost *out, pic_tokens *tokens) {
sqlite3 *db = NULL;
sqlite3_stmt *q = NULL;
pic_tokens t;
int rc = -1;
memset(&t, 0, sizeof t);
memset(out, 0, sizeof *out);
if (!raw_usage || sqlite3_open(":memory:", &db) != SQLITE_OK) {
sqlite3_close(db);
return -1;
}
#define X(path) "json_extract(?1,'$." path "')"
if (sqlite3_prepare_v2(db,
"SELECT coalesce(" X("input_tokens") ",0), coalesce(" X("output_tokens") ",0),"
" coalesce(" X("cache_read_input_tokens") ",0), coalesce(" X("cache_creation_input_tokens") ",0),"
" coalesce(" X("cache_creation.ephemeral_1h_input_tokens") ",0),"
" coalesce(" X("prompt_tokens") ",0), coalesce(" X("completion_tokens") ",0),"
" coalesce(" X("prompt_tokens_details.cached_tokens") "," X("prompt_cache_hit_tokens") ","
" " X("cached_tokens") ",0),"
" coalesce(" X("prompt_tokens_details.cache_write_tokens") ",0),"
" coalesce(" X("input_tokens_details.cached_tokens") ",0),"
" coalesce(" X("input_tokens_details.cache_write_tokens") ",0),"
" " X("cost") ", " X("is_byok") ", " X("cost_details.upstream_inference_cost") ","
" " X("cost_details.upstream_inference_prompt_cost") ","
" " X("cost_details.upstream_inference_completions_cost") ","
" json_type(?1,'$.cost_details') = 'object',"
" coalesce(" X("total_tokens") ",0)"
" WHERE json_valid(?1) AND json_type(?1) = 'object'",
-1, &q, NULL) != SQLITE_OK) {
sqlite3_close(db);
return -1;
}
#undef X
sqlite3_bind_text(q, 1, raw_usage, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
double prompt = sqlite3_column_double(q, 5);
rc = 0;
if (api_is(m, API_MESSAGES)) {
t.input = sqlite3_column_double(q, 0);
t.output = sqlite3_column_double(q, 1);
t.cache_read = sqlite3_column_double(q, 2);
t.cache_write = sqlite3_column_double(q, 3);
t.cache_write_1h = sqlite3_column_double(q, 4);
t.total = t.input + t.output + t.cache_read + t.cache_write;
} else if (api_is(m, API_CHAT)) {
t.cache_read = sqlite3_column_double(q, 7);
t.cache_write = sqlite3_column_double(q, 8);
t.input = positive(prompt - t.cache_read - t.cache_write);
t.output = sqlite3_column_double(q, 6);
t.total = t.input + t.output + t.cache_read + t.cache_write;
} else {
t.cache_read = sqlite3_column_double(q, 9);
t.cache_write = sqlite3_column_double(q, 10);
t.input = positive(sqlite3_column_double(q, 0) - t.cache_read - t.cache_write);
t.output = sqlite3_column_double(q, 1);
t.total = sqlite3_column_double(q, 17); /* Pi takes the provider's total here */
}
pic_cost_calc(&m->price, &t, out);
if (tokens) {
*tokens = t;
}
/* OpenRouter's billed cost, when its accounting is complete. */
if (api_is(m, API_CHAT) && (strcmp(m->provider, "openrouter") == 0 || strstr(m->base_url, "openrouter.ai")) &&
valid_cost(q, 11)) {
int byok = sqlite3_column_type(q, 12) != SQLITE_NULL ? (int)sqlite3_column_int(q, 12) : -1;
if (byok == 0) {
out->total = sqlite3_column_double(q, 11);
out->total_from_provider = 1;
} else if (byok == 1 && sqlite3_column_int(q, 16)) {
int have_upstream = sqlite3_column_type(q, 13) != SQLITE_NULL;
double upstream = sqlite3_column_double(q, 13);
if (!have_upstream && valid_cost(q, 14) && valid_cost(q, 15)) {
upstream = sqlite3_column_double(q, 14) + sqlite3_column_double(q, 15);
have_upstream = 1;
}
if (have_upstream && upstream >= 0 && isfinite(upstream)) {
out->total = sqlite3_column_double(q, 11) + upstream;
out->total_from_provider = 1;
}
}
}
}
sqlite3_finalize(q);
sqlite3_close(db);
return rc;
}
void pic_cost_json(const pic_cost *c, char *out, size_t cap) {
(void)snprintf(out, cap, "{\"input\":%.15g,\"output\":%.15g,\"cacheRead\":%.15g,\"cacheWrite\":%.15g,\"total\":%.15g%s}",
c->input, c->output, c->cache_read, c->cache_write, c->total,
c->total_from_provider ? ",\"totalFromProvider\":true" : "");
}
static char *models_priced(const pic_model *m, const char *raw_usage) {
pic_cost c;
pic_tokens t;
char cost[256], tok[256], *out;
sqlite3 *db = NULL;
if (pic_usage_cost(m, raw_usage, &c, &t) != 0 || sqlite3_open(":memory:", &db) != SQLITE_OK) {
sqlite3_close(db);
return NULL;
}
pic_cost_json(&c, cost, sizeof cost);
(void)snprintf(tok, sizeof tok, "{\"input\":%.0f,\"output\":%.0f,\"cacheRead\":%.0f,\"cacheWrite\":%.0f,\"totalTokens\":%.0f}",
t.input, t.output, t.cache_read, t.cache_write, t.total);
out = sql_text(db, "SELECT json_set(?1, '$.pic_cost', json(?2), '$.pic_tokens', json(?3))", raw_usage, cost, tok);
sqlite3_close(db);
return out;
}
/* ---- resolution ------------------------------------------------------- */
static int models_resolve(const char *name, pic_model *out, char *err, size_t errcap) {
char path[1024] = "", *file, *prov_obj = NULL, *model_obj = NULL, *s;
char *cat_obj = NULL, endpoint_url[PIC_ENDPOINT_URL_CAP] = "";
const provider_def *builtin = NULL;
size_t best = 0;
sqlite3 *db = NULL;
int rc = -1;
long v;
memset(out, 0, sizeof *out);
file = user_models(path, sizeof path);
if (sqlite3_open(":memory:", &db) != SQLITE_OK) {
(void)snprintf(err, errcap, "out of memory");
free(file);
return -1;
}
if (file) {
char *valid = sql_text(db, "SELECT 1 WHERE json_valid(?1)", file, NULL, NULL);
if (!valid) {
(void)snprintf(err, errcap, "%s is not valid JSON", path);
goto done;
}
free(valid);
}
/* The longest provider name that prefixes NAME followed by '/'. Provider
* names may themselves contain '/', so user providers are checked too. */
for (size_t i = 0; i < sizeof providers / sizeof providers[0]; i++) {
size_t n = strlen(providers[i].name);
if (n > best && strncmp(name, providers[i].name, n) == 0 && name[n] == '/') {
best = n;
builtin = &providers[i];
copy(out->provider, sizeof out->provider, providers[i].name);
}
}
if (file) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(db, "SELECT key FROM json_each(?, '$.providers')", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, file, -1, SQLITE_STATIC);
while (sqlite3_step(q) == SQLITE_ROW) {
const char *k = (const char *)sqlite3_column_text(q, 0);
size_t n = strlen(k);
if (n > best && strncmp(name, k, n) == 0 && name[n] == '/') {
/* ':' separates a key's name from its provider's (cred.h), and a
* name never shortens to another provider's. */
if (strchr(k, ':') || n >= sizeof out->provider) {
(void)snprintf(err, errcap, "%s: the provider %.80s%s: a provider name has no ':' and is at most %zu bytes",
path, k, n > 80 ? "..." : "", sizeof out->provider - 1);
sqlite3_finalize(q);
goto done;
}
best = n;
builtin = NULL;
copy(out->provider, sizeof out->provider, k);
}
}
sqlite3_finalize(q);
}
if (best) {
for (size_t i = 0; !builtin && i < sizeof providers / sizeof providers[0]; i++) {
if (strcmp(providers[i].name, out->provider) == 0) {
builtin = &providers[i];
}
}
}
}
/* A saved endpoint (endpoints.h): only when no provider has the name, which adding one
* refuses, so a provider added later to the models file takes it back. */
if (!best && strchr(name, '/')) {
size_t n = (size_t)(strchr(name, '/') - name);
char prefix[PIC_CRED_PROVIDER_CAP];
if (n < sizeof prefix) {
(void)snprintf(prefix, sizeof prefix, "%.*s", (int)n, name);
if (pic_endpoint_url(prefix, endpoint_url, sizeof endpoint_url)) {
best = n;
copy(out->provider, sizeof out->provider, prefix);
}
}
}
if (best) {
copy(out->id, sizeof out->id, name + best + 1);
} else if (strncmp(name, "claude-", 7) == 0) {
builtin = &providers[0]; /* a bare Claude model id means Anthropic */
copy(out->provider, sizeof out->provider, "anthropic");
copy(out->id, sizeof out->id, name);
} else {
(void)snprintf(err, errcap, "unknown model %s: name it as provider/model (e.g. openrouter/%s)", name, name);
goto done;
}
if (!out->id[0]) {
(void)snprintf(err, errcap, "model name %s has no model after the provider", name);
goto done;
}
if (endpoint_url[0]) { /* an OpenAI-compatible server; its key is the store's row under its name */
copy(out->api, sizeof out->api, API_CHAT);
copy(out->base_url, sizeof out->base_url, endpoint_url);
} else if (builtin) {
copy(out->api, sizeof out->api, builtin->api);
copy(out->base_url, sizeof out->base_url, builtin->base_url);
copy(out->key_env, sizeof out->key_env, builtin->key_env);
}
out->context_window = 128000;
out->max_tokens = 16384;
for (size_t i = 0; i < sizeof known_models / sizeof known_models[0]; i++) {
if (strcmp(known_models[i].provider, out->provider) == 0 && strcmp(known_models[i].id, out->id) == 0) {
out->context_window = known_models[i].context_window;
out->max_tokens = known_models[i].max_tokens;
out->reasoning = known_models[i].reasoning;
out->image_input = 1; /* every one takes text and images */
}
}
if (file) {
prov_obj = sql_text(db, "SELECT json_extract(?1, '$.providers.\"' || ?2 || '\"')", file, out->provider, NULL);
model_obj = prov_obj ? sql_text(db, "SELECT value FROM json_each(?1, '$.models') WHERE json_extract(value, '$.id') = ?2",
prov_obj, out->id, NULL)
: NULL;
if (!model_obj && prov_obj) {
model_obj = sql_text(db, "SELECT json_extract(?1, '$.modelOverrides.\"' || ?2 || '\"')", prov_obj, out->id, NULL);
}
}
if (!builtin && !prov_obj && !endpoint_url[0]) {
(void)snprintf(err, errcap, "unknown provider %s", out->provider);
goto done;
}
/* Pi's catalog entry for the model (its API, endpoint, limits, compat),
* then the models file: the provider's fields, then the model's own. */
cat_obj = endpoint_url[0] ? NULL : pic_catalog_find(out->provider, out->id);
for (int level = 0; level < 3; level++) {
const char *obj = level == 0 ? cat_obj : level == 1 ? prov_obj : model_obj;
if (!obj) {
continue;
}
if ((s = field(db, obj, "$.baseUrl"))) {
copy(out->base_url, sizeof out->base_url, s);
free(s);
}
if ((s = field(db, obj, "$.api"))) {
int bad = !api_known(s);
if (!bad) {
copy(out->api, sizeof out->api, s);
}
if (bad) {
(void)snprintf(err, errcap, "%s: api %s is not supported (anthropic-messages, openai-completions, "
"openai-responses, google-generative-ai)", path, s);
}
free(s);
if (bad) {
goto done;
}
}
if (level > 0 && (s = field(db, obj, "$.apiKey"))) {
int bad = apply_key(s, out, err, errcap) != 0;
free(s);
if (bad) {
goto done;
}
}
if (number(db, obj, "$.reasoning", &v)) {
out->reasoning = (int)v;
}
if (number(db, obj, "$.contextWindow", &v) && v > 0) {
out->context_window = v;
}
if ((s = sql_text(db, "SELECT CASE json_type(?1, '$.input') WHEN 'array' THEN EXISTS (SELECT 1 FROM"
" json_each(?1, '$.input') WHERE value = 'image') END", obj, NULL, NULL))) {
out->image_input = strcmp(s, "1") == 0;
free(s);
}
if (number(db, obj, "$.maxTokens", &v) && v > 0) {
out->max_tokens = v;
}
apply_thinking_map(db, obj, out);
apply_price(db, obj, &out->price);
if ((s = sql_text(db, "SELECT json_extract(?1, '$.headers')", obj, NULL, NULL))) {
apply_headers(db, s, out);
free(s);
}
}
if (!out->base_url[0]) {
(void)snprintf(err, errcap, "provider %s has no baseUrl", out->provider);
goto done;
}
{
size_t n = strlen(out->base_url);
while (n > 0 && out->base_url[n - 1] == '/') {
out->base_url[--n] = '\0';
}
}
detect_compat(out);
for (int level = 0; level < 3; level++) {
const char *obj = level == 0 ? cat_obj : level == 1 ? prov_obj : model_obj;
if (obj && (s = sql_text(db, "SELECT json_extract(?1, '$.compat')", obj, NULL, NULL))) {
apply_compat(db, s, &out->compat);
free(s);
}
}
rc = 0;
done:
free(cat_obj);
free(prov_obj);
free(model_obj);
free(file);
sqlite3_close(db);
return rc;
}
int pic_model_available(const char *provider) {
char name[128], err[256];
pic_model m;
(void)snprintf(name, sizeof name, "%s/x", provider);
if (models_resolve(name, &m, err, sizeof err) != 0) {
return 0;
}
if (m.key_literal[0] || !m.key_env[0]) {
return 1;
}
{
const char *v = getenv(m.key_env);
return (v && *v) || pic_cred_stored(provider); /* a row: nothing is unlocked to ask */
}
}
void pic_provider_source(const char *provider, char *out, size_t cap) {
char name[128], err[256];
pic_model m;
(void)snprintf(name, sizeof name, "%s/x", provider);
if (models_resolve(name, &m, err, sizeof err) != 0) {
(void)snprintf(out, cap, "unknown");
return;
}
pic_cred_describe(provider, m.key_env, m.key_literal, out, cap);
}
int pic_providers_each(int (*fn)(void *ctx, const char *provider), void *ctx) {
char path[1024];
char *file;
sqlite3 *db = NULL;
sqlite3_stmt *q = NULL;
for (size_t i = 0; i < sizeof providers / sizeof providers[0]; i++) {
if (fn(ctx, providers[i].name)) {
return 0;
}
}
if (!(file = user_models(path, sizeof path))) {
return 0;
}
if (sqlite3_open(":memory:", &db) == SQLITE_OK &&
sqlite3_prepare_v2(db, "SELECT key FROM json_each(?1, '$.providers') WHERE json_valid(?1) ORDER BY key", -1, &q,
NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, file, -1, SQLITE_STATIC);
while (sqlite3_step(q) == SQLITE_ROW) {
const char *name = (const char *)sqlite3_column_text(q, 0);
int builtin = 0;
for (size_t i = 0; i < sizeof providers / sizeof providers[0]; i++) {
builtin |= strcmp(providers[i].name, name) == 0;
}
if (!builtin && !strchr(name, ':') && strlen(name) < sizeof ((pic_model *)0)->provider && fn(ctx, name)) {
break;
}
}
}
sqlite3_finalize(q);
sqlite3_close(db);
free(file);
return 0;
}
int pic_models_each_user(int (*fn)(void *ctx, const char *provider, const char *json), void *ctx) {
char path[1024];
char *file = user_models(path, sizeof path);
sqlite3 *db = NULL;
sqlite3_stmt *q = NULL;
int stop = 0;
if (!file) {
return 0;
}
if (sqlite3_open(":memory:", &db) == SQLITE_OK &&
sqlite3_prepare_v2(db,
"SELECT p.key, m.value FROM json_each(?1, '$.providers') p, json_each(p.value, '$.models') m"
" WHERE json_valid(?1) AND json_type(m.value, '$.id') = 'text'",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, file, -1, SQLITE_STATIC);
while (!stop && sqlite3_step(q) == SQLITE_ROW) {
stop = fn(ctx, (const char *)sqlite3_column_text(q, 0), (const char *)sqlite3_column_text(q, 1));
}
}
sqlite3_finalize(q);
sqlite3_close(db);
free(file);
return 0;
}
const pic_model_source pic_models_source = {models_resolve, models_priced};