Artifact b5bab367c5206fd0ad829709d3dce8821a192318b2ef3e06a7b491e19c023be6:
- File
src/models.c
— part of check-in
[fb82c37817]
at
2026-11-19 14:01:47
on branch models
— Model picker, slash command menu and Pi's model catalog
Models are chosen as in Pi. pic carries a snapshot of Pi's catalog for its providers (653 chat models; tools/model-catalog.sh regenerates it from pi.dev/api/models) and lays fresher per-provider lists from pi.dev over it, cached in ~/.pic/models-store.json with ETags and trusted for four hours, used only when newer than the snapshot. Resolution takes a model's API, endpoint, limits and compat settings from the catalog before the models file. pic models lists the models of providers with a key (--all every one, --json, --refresh); pic models --default saves the model used when none is given.
In the terminal interface, Ctrl+L or /model opens a picker of the models whose provider has a key, filtered by Pi's fuzzy matching as you type, current and default first; Enter uses the model, Ctrl+S also saves it as the default; Ctrl+P cycles. Typing / shows a menu of commands with their arguments (Tab completes, Enter runs) and /model completes model names. New commands show the conversation's details and token counts, copy the last reply (OSC 52 and the system clipboard), export, clone and list the hotkeys. (user: dmestas, size: 18222) [annotate] [blame] [check-ins using] [more...]
/* 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include "models.h" #include "catalog.h" #include "sqlite3.h" typedef struct { const char *name, *base_url, *key_env; pic_api api; } provider_def; static const provider_def providers[] = { {"anthropic", "https://api.anthropic.com", "ANTHROPIC_API_KEY", PIC_API_ANTHROPIC}, {"openai", "https://api.openai.com/v1", "OPENAI_API_KEY", PIC_API_RESPONSES}, {"openrouter", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY", PIC_API_CHAT}, {"xai", "https://api.x.ai/v1", "XAI_API_KEY", PIC_API_RESPONSES}, {"groq", "https://api.groq.com/openai/v1", "GROQ_API_KEY", PIC_API_CHAT}, {"cerebras", "https://api.cerebras.ai/v1", "CEREBRAS_API_KEY", PIC_API_CHAT}, {"deepseek", "https://api.deepseek.com", "DEEPSEEK_API_KEY", PIC_API_CHAT}, {"together", "https://api.together.ai/v1", "TOGETHER_API_KEY", PIC_API_CHAT}, {"fireworks", "https://api.fireworks.ai/inference/v1", "FIREWORKS_API_KEY", PIC_API_CHAT}, {"huggingface", "https://router.huggingface.co/v1", "HF_TOKEN", PIC_API_CHAT}, {"nvidia", "https://integrate.api.nvidia.com/v1", "NVIDIA_API_KEY", PIC_API_CHAT}, {"moonshotai", "https://api.moonshot.ai/v1", "MOONSHOT_API_KEY", PIC_API_CHAT}, {"zai", "https://api.z.ai/api/coding/paas/v4", "ZAI_API_KEY", PIC_API_CHAT}, }; /* 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}, }; static void copy(char *dst, size_t cap, const char *src) { (void)snprintf(dst, cap, "%s", src ? src : ""); } const char *pic_api_name(pic_api api) { return api == PIC_API_ANTHROPIC ? "anthropic-messages" : api == PIC_API_CHAT ? "openai-completions" : "openai-responses"; } static int api_from_name(const char *s, pic_api *out) { if (strcmp(s, "anthropic-messages") == 0) { *out = PIC_API_ANTHROPIC; } else if (strcmp(s, "openai-completions") == 0) { *out = PIC_API_CHAT; } else if (strcmp(s, "openai-responses") == 0) { *out = PIC_API_RESPONSES; } else { return -1; } return 0; } void pic_model_url(const pic_model *m, char *out, size_t cap) { (void)snprintf(out, cap, "%s%s", m->base_url, m->api == PIC_API_ANTHROPIC ? "/v1/messages" : m->api == PIC_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->anthropic_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) { FILE *f = fopen(path, "rb"); char *buf; long n; if (!f) { return NULL; } if (fseek(f, 0, SEEK_END) != 0 || (n = ftell(f)) < 0 || n > (1 << 22) || fseek(f, 0, SEEK_SET) != 0 || !(buf = malloc((size_t)n + 1))) { fclose(f); return NULL; } if (fread(buf, 1, (size_t)n, f) != (size_t)n) { free(buf); fclose(f); return NULL; } buf[n] = '\0'; fclose(f); return buf; } /* ~/.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, "$.supportsReasoningEffort", &v)) { c->supports_reasoning_effort = (int)v; } if (number(db, compat, "$.requiresReasoningContentOnAssistantMessages", &v)) { c->requires_reasoning_content = (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); } } /* "$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); } /* ---- resolution ------------------------------------------------------- */ int pic_model_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; 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 && !sql_text(db, "SELECT 1 WHERE json_valid(?1)", file, NULL, NULL)) { (void)snprintf(err, errcap, "%s is not valid JSON", path); goto done; } /* 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] == '/') { 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]; } } } } 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 (builtin) { 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; } } 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) { (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 = 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_from_name(s, &out->api) != 0; if (bad) { (void)snprintf(err, errcap, "%s: api %s is not supported (anthropic-messages, openai-completions, " "openai-responses)", 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 (number(db, obj, "$.maxTokens", &v) && v > 0) { out->max_tokens = v; } 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 (pic_model_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; } } 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; }