Skip to content
pi-c Documentation
Login

Documentation

/* Chat Completions adapter (OpenAI, OpenRouter, OpenAI-compatible servers):
 * the request built from the journal as Pi's openai-completions adapter
 * builds it, streamed through the shared POST and the chunk decoder. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "anthropic.h"
#include "openai_chat.h"
#include "provider_http.h"


typedef struct {
    pic_model model;
    char *url, *workspace;
    pic_net *net;
} pch_state;

/* Images from a run of tool results (a "tool" message carries text only) go
 * after it in one user message, as Pi sends them. */
static void flush_tool_images(sqlite3_str *out, sqlite3_str *pending, int *first) {
    if (sqlite3_str_length(pending) == 0) {
        return;
    }
    sqlite3_str_appendall(out, *first ? "" : ",");
    sqlite3_str_appendall(out, "{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":"
                               "\"Attached image(s) from tool result:\"},");
    sqlite3_str_appendall(out, sqlite3_str_value(pending));
    sqlite3_str_appendall(out, "]}");
    sqlite3_str_reset(pending);
    *first = 0;
}

/* One element per message: the system prompt, the user's text, each
 * assistant turn (verbatim to its own model, else rebuilt from the neutral
 * form: text joined, tool calls with normalised ids and arguments as a JSON
 * string, no reasoning), and each tool result as a "tool" message. */
static char *pch_build_messages(pic_store *s, const pch_state *st, int64_t submission, const char *system_prompt, char *err,
                            size_t errcap) {
    sqlite3_stmt *q = NULL;
    sqlite3_str *out = sqlite3_str_new(s->db), *pending = sqlite3_str_new(s->db);
    const pic_compat *c = &st->model.compat;
    int step, first = 1;
    if (sqlite3_prepare_v2(
            s->db,
            PIC_CONTEXT_CTE "SELECT CASE e.kind"
            " WHEN 'user' THEN json_object('role','user','content',"
            "   coalesce(json(pic_content(e.seq,e.body,'chat-user',?6,?9)),e.body))"
            " WHEN 'compaction' THEN json_object('role','user','content'," PIC_SUMMARY_SQL("e.body") ")"
            " WHEN 'branch_summary' THEN json_object('role','user','content'," PIC_BRANCH_SUMMARY_SQL("e.body") ")"
            " WHEN 'instructions' THEN json_object('role','user','content',"
            "   '<project_instructions_update>' || char(10) || e.body || char(10) || '</project_instructions_update>')"
            " WHEN 'hook' THEN json_object('role','user','content',e.body)"
            " WHEN 'tool_result' THEN json_object('role','tool','tool_call_id',"
            "   CASE WHEN a.seq > kk.cseq AND a.provider IS ?2 AND a.api IS ?3 AND a.model IS ?4 THEN f.call_id"
            "   ELSE pic_norm_id(f.call_id,'openai-completions',?2) END,"
            "   'content',coalesce(json(pic_content(e.seq,e.body,'chat-tool',?6,?9)),e.body))"
            " ELSE CASE WHEN v.fresh AND e.provider IS ?2 AND e.api IS ?3 AND e.model IS ?4 THEN json(e.native)"
            "   ELSE (SELECT CASE WHEN t IS NULL AND n = 0 THEN NULL ELSE json_patch("
            "       json_object('role','assistant','content',t),"
            "       json_object('tool_calls',CASE WHEN n = 0 THEN NULL ELSE json(calls) END,"
            "         'reasoning_content',CASE WHEN ?5 THEN '' END)) END"
            "     FROM (SELECT (SELECT group_concat(json_extract(value,'$.text'),'') FROM json_each(e.body)"
            "             WHERE json_extract(value,'$.type')='text') AS t,"
            "           (SELECT count(*) FROM json_each(e.body) WHERE json_extract(value,'$.type')='toolCall') AS n,"
            "           (SELECT json_group_array(json_object('id',pic_norm_id(json_extract(value,'$.id'),"
            "               'openai-completions',?2),'type','function','function',json_object('name',"
            "               json_extract(value,'$.name'),'arguments',json_extract(value,'$.arguments') || '')))"
            "             FROM json_each(e.body) WHERE json_extract(value,'$.type')='toolCall') AS calls)) END END,"
            " e.kind = 'tool_result', CASE e.kind WHEN 'tool_result' THEN pic_content(e.seq,e.body,'chat-tool-images',?6,?9) END"
            " FROM pic_entry e JOIN v ON v.seq = e.seq CROSS JOIN kk LEFT JOIN pic_effect f ON f.id=e.effect_id"
            " LEFT JOIN pic_entry a ON a.seq=f.entry_seq ORDER BY e.kind != 'compaction', e.seq",
            -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "sql: %s", sqlite3_errmsg(s->db));
        sqlite3_free(sqlite3_str_finish(out));
        sqlite3_free(sqlite3_str_finish(pending));
        return NULL;
    }
    sqlite3_bind_int64(q, 1, submission);
    sqlite3_bind_text(q, 2, st->model.provider, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, st->model.api, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 4, st->model.id, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 5, c->requires_reasoning_content);
    sqlite3_bind_int(q, 6, st->model.image_input);
    sqlite3_bind_int64(q, 9, pic_image_budget(s, submission));
    {
        /* The system prompt: developer role for reasoning models where the
         * server takes it, as Pi does. */
        sqlite3_stmt *sp = NULL;
        if (sqlite3_prepare_v2(s->db, "SELECT json_object('role',?1,'content',?2)", -1, &sp, NULL) == SQLITE_OK) {
            sqlite3_bind_text(sp, 1, st->model.reasoning && c->supports_developer_role ? "developer" : "system", -1,
                              SQLITE_STATIC);
            sqlite3_bind_text(sp, 2, system_prompt, -1, SQLITE_STATIC);
            if (sqlite3_step(sp) == SQLITE_ROW) {
                sqlite3_str_appendall(out, "[");
                sqlite3_str_appendall(out, (const char *)sqlite3_column_text(sp, 0));
                first = 0;
            }
            sqlite3_finalize(sp);
        }
    }
    if (first) {
        sqlite3_str_appendall(out, "[");
    }
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *item = (const char *)sqlite3_column_text(q, 0);
        const char *images = (const char *)sqlite3_column_text(q, 2);
        if (!sqlite3_column_int(q, 1)) {
            flush_tool_images(out, pending, &first);
        }
        if (images) { /* a JSON array of image parts */
            sqlite3_str_appendall(pending, sqlite3_str_length(pending) ? "," : "");
            sqlite3_str_append(pending, images + 1, (int)strlen(images) - 2);
        }
        if (!item) {
            continue; /* a foreign turn with nothing this API can take */
        }
        sqlite3_str_appendall(out, first ? "" : ",");
        sqlite3_str_appendall(out, item);
        first = 0;
    }
    sqlite3_finalize(q);
    flush_tool_images(out, pending, &first);
    if (sqlite3_str_errcode(pending) != SQLITE_OK) {
        step = SQLITE_NOMEM;
    }
    sqlite3_free(sqlite3_str_finish(pending));
    sqlite3_str_appendall(out, "]");
    if (step != SQLITE_DONE || sqlite3_str_errcode(out) != SQLITE_OK) {
        (void)snprintf(err, errcap, "could not build the request: %s", sqlite3_errmsg(s->db));
        sqlite3_free(sqlite3_str_finish(out));
        return NULL;
    }
    return sqlite3_str_finish(out);
}

/* Pi's cache_control marks for OpenRouter's anthropic/... models: the text of
 * the first system or developer message (WHICH 0) or of the last user,
 * assistant or tool message that has text (WHICH 1). A string becomes a text
 * part carrying the mark; in an array the last text part takes it. Returns
 * the new array (sqlite3_malloc'd), or NULL. */
static char *mark_text(sqlite3 *db, const char *messages, int which, const char *cc) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(
            db,
            "WITH m(k, r, c) AS (SELECT key, json_extract(value,'$.role'), value FROM json_each(?1)"
            "  WHERE json_type(value,'$.content') = 'text' AND json_extract(value,'$.content') != ''"
            "     OR json_type(value,'$.content') = 'array'"
            "        AND EXISTS (SELECT 1 FROM json_each(value,'$.content') WHERE json_extract(value,'$.type') = 'text')),"
            " t(i) AS (SELECT CASE ?3 WHEN 0 THEN (SELECT min(k) FROM m WHERE r IN ('system','developer'))"
            "   ELSE (SELECT max(k) FROM m WHERE r IN ('user','assistant','tool')) END)"
            "SELECT CASE WHEN i IS NULL THEN ?1"
            " WHEN json_type(?1, printf('$[%d].content', i)) = 'text' THEN json_set(?1, printf('$[%d].content', i),"
            "   json_array(json_object('type','text','text',json_extract(?1, printf('$[%d].content', i)),'cache_control',json(?2))))"
            " ELSE json_set(?1, printf('$[%d].content[%d].cache_control', i,"
            "   (SELECT max(key) FROM json_each(?1, printf('$[%d].content', i)) WHERE json_extract(value,'$.type') = 'text')),"
            "   json(?2)) END FROM t",
            -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, messages, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, cc, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 3, which);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        out = sqlite3_mprintf("%s", (const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

/* The thinking fields by Pi's thinkingFormat, for a request at LEVEL. */
static char *pch_build_body(pic_store *s, const pch_state *st, const char *level, const char *messages, const char *tools,
                        const char *session) {
    const pic_compat *c = &st->model.compat;
    pic_cache retention = pic_cache_retention();
    const char *cc = c->cache_control && retention != PIC_CACHE_NONE
                         ? pic_anthropic_cache_control(retention == PIC_CACHE_LONG && c->supports_long_cache)
                         : NULL;
    /* Pi's prompt_cache_key: OpenAI itself, or any server that takes long retention when it is asked for. */
    int key = retention != PIC_CACHE_NONE && session &&
              (strstr(st->model.base_url, "api.openai.com") || (retention == PIC_CACHE_LONG && c->supports_long_cache));
    int ttl24 = retention == PIC_CACHE_LONG && c->supports_long_cache;
    char *marked = NULL, *sys = NULL;
    sqlite3_stmt *q = NULL;
    char *body = NULL;
    const char *fmt = c->thinking_format;
    int reasoning = st->model.reasoning, on = strcmp(level, "off") != 0;
    const char *off_value = NULL;
    int off_state = pic_model_thinking_map(&st->model, "off", &off_value);
    if (cc) {
        sys = mark_text(s->db, messages, 0, cc);
        marked = sys ? mark_text(s->db, sys, 1, cc) : NULL;
        if (!marked) {
            sqlite3_free(sys);
            return NULL;
        }
        messages = marked;
    }
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT CASE WHEN json_array_length(?3) = 0 THEN json_remove(b,'$.tools') ELSE b END FROM (SELECT json_patch(json_object('model',?1,'messages',json(?2),'stream',json('true'),"
            "  'tools',json((SELECT json_group_array(json_object('type','function','function',json_object("
            "    'name',json_extract(value,'$.name'),'description',json_extract(value,'$.description'),"
            "    'parameters',json(json_extract(value,'$.input_schema'))))) FROM json_each(?3)))),"
            " json_object('prompt_cache_key',CASE WHEN ?13 THEN substr(?14,1,64) END,"
            "  'prompt_cache_retention',CASE WHEN ?15 THEN '24h' END,"
            "  'stream_options',CASE WHEN ?4 THEN json_object('include_usage',json('true')) END,"
            "  'store',CASE WHEN ?5 THEN json('false') END,"
            "  'reasoning_effort',CASE WHEN ?6 AND ?8 AND ?10 AND ?7 IN ('openai','zai','qwen','deepseek','together') THEN ?9"
            "    WHEN ?6 AND ?8 AND NOT ?10 AND ?7 = 'openai' AND ?11 = 2 THEN ?12 END,"
            "  'reasoning',CASE WHEN ?6 AND ?7 = 'openrouter' THEN CASE WHEN ?10 THEN json_object('effort',?9)"
            "      WHEN ?11 != 1 THEN json_object('effort',coalesce(?12,'none')) END"
            "    WHEN ?6 AND ?7 = 'together' THEN json_object('enabled',json(iif(?10,'true','false'))) END,"
            "  'thinking',CASE WHEN ?6 AND ?7 = 'deepseek' THEN CASE WHEN ?10 THEN json_object('type','enabled')"
            "      WHEN ?11 != 1 THEN json_object('type','disabled') END"
            "    WHEN ?6 AND ?7 = 'zai' THEN CASE WHEN ?10 THEN json_object('type','enabled','clear_thinking',json('false'))"
            "      ELSE json_object('type','disabled') END END,"
            "  'enable_thinking',CASE WHEN ?6 AND ?7 = 'qwen' THEN json(iif(?10,'true','false')) END)) AS b)",
            -1, &q, NULL) != SQLITE_OK) {
        sqlite3_free(marked);
        return NULL;
    }
    sqlite3_bind_text(q, 2, messages, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 1, st->model.id, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 13, key);
    sqlite3_bind_text(q, 14, session ? session : "", -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 15, ttl24);
    sqlite3_bind_text(q, 3, tools, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 4, c->supports_usage_in_streaming);
    sqlite3_bind_int(q, 5, c->supports_store);
    sqlite3_bind_int(q, 6, reasoning);
    sqlite3_bind_text(q, 7, fmt, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 8, c->supports_reasoning_effort);
    if (on) {
        sqlite3_bind_text(q, 9, pic_model_thinking_effort(&st->model, level), -1, SQLITE_STATIC);
    }
    sqlite3_bind_int(q, 10, on);
    sqlite3_bind_int(q, 11, off_state);
    if (off_state == 2) {
        sqlite3_bind_text(q, 12, off_value, -1, SQLITE_STATIC);
    }
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        body = pic_strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    sqlite3_free(marked);
    if (body && cc) { /* the last tool takes the mark too */
        char *with = pic_json_body(s->db,
                                   "SELECT CASE WHEN json_array_length(?1,'$.tools') > 0"
                                   " THEN json_set(?1,'$.tools[#-1].cache_control',json(?2)) ELSE ?1 END",
                                   2, body, cc);
        free(body);
        body = with;
    }
    return body;
}

typedef struct {
    sqlite3 *db;
    pic_chat dec;
    pic_store *stream; /* replies only: deltas go to its events */
} pch_decoding;

static int pch_dec_begin(void *ctx) {
    pch_decoding *d = ctx;
    if (pic_chat_init(&d->dec, d->db) != 0) {
        return -1;
    }
    if (d->stream) {
        d->dec.on_delta = pic_ev_delta;
        d->dec.delta_ctx = d->stream;
    }
    return 0;
}

static int pch_dec_finish(void *ctx, char *why, size_t cap) {
    pch_decoding *d = ctx;
    if (pic_chat_finish(&d->dec) == 0) {
        return 0;
    }
    (void)snprintf(why, cap, "%s", d->dec.err);
    return -1;
}

static int pch_dec_event(void *ctx, const char *event, const char *data, size_t len) {
    return pic_chat_event(&((pch_decoding *)ctx)->dec, event, data, len);
}

static void pch_dec_end(void *ctx) { pic_chat_free(&((pch_decoding *)ctx)->dec); }

static int chat_reply(pic_provider *p, pic_store *s, int64_t submission, int64_t turn, pic_reply *out, int *retryable,
                      char *err, size_t errcap) {
    pch_state *st = p->state;
    static const char *const extra[] = {"Accept: text/event-stream"};
    pch_decoding d;
    pic_stream_decoder dec = {pch_dec_begin, pch_dec_event, pch_dec_finish, pch_dec_end, &d};
    char *messages = NULL, *body = NULL, request_id[128], *system_prompt = pic_session_text(s, submission, "system_prompt"),
         *tools = pic_session_text(s, submission, "tools"), *session = pic_session_id(s, submission);
    int rc;
    (void)turn;
    *retryable = 0;
    memset(out, 0, sizeof *out);
    memset(&d, 0, sizeof d);
    d.db = s->db;
    d.stream = s;
    if (system_prompt) {
        messages = pch_build_messages(s, st, submission, system_prompt, err, errcap);
    }
    body = messages && tools ? pch_build_body(s, st, p->thinking, messages, tools, session) : NULL;
    sqlite3_free(messages);
    free(session);
    free(system_prompt);
    free(tools);
    if (!body) {
        if (!err[0]) {
            (void)snprintf(err, errcap, "could not build the request body");
        }
        return -1;
    }
    rc = pic_stream_post(st->net, s, &st->model, st->url, PIC_AUTH_BEARER, extra, 1, body, &dec, request_id,
                         sizeof request_id, retryable, err, errcap);
    free(body);
    if (rc != 0) {
        return -1;
    }
    out->native = pic_chat_native(&d.dec);
    out->neutral = pic_chat_neutral(&d.dec);
    out->stop_reason = pic_strdup(pic_chat_stop(&d.dec));
    out->usage = d.dec.usage ? pic_strdup(d.dec.usage) : NULL;
    out->request_id = request_id[0] ? pic_strdup(request_id) : NULL;
    out->provider = pic_strdup(st->model.provider);
    out->api = pic_strdup(st->model.api);
    out->model = pic_strdup(st->model.id);
    pch_dec_end(&d);
    if (!out->native || !out->neutral || !out->stop_reason || !out->provider || !out->api || !out->model) {
        pic_reply_free(out);
        (void)snprintf(err, errcap, "could not assemble the reply");
        return -1;
    }
    return 0;
}

/* A plain request for compaction: SYSTEM and one USER message, no tools. */
static int chat_summarize(pic_provider *p, pic_store *s, const char *system, const char *user, char **text,
                             char **usage, int *retryable, char *err, size_t errcap) {
    pch_state *st = p->state;
    static const char *const extra[] = {"Accept: text/event-stream"};
    pch_decoding d;
    pic_stream_decoder dec = {pch_dec_begin, pch_dec_event, pch_dec_finish, pch_dec_end, &d};
    char *body, *neutral;
    int rc;
    *text = *usage = NULL;
    memset(&d, 0, sizeof d);
    d.db = s->db;
    body = pic_json_body(s->db, "SELECT json_object('model',?1,'messages',json_array(json_object('role','system','content',?2),json_object('role','user','content',?3)),'stream',json('true'))", 3, st->model.id, system, user);
    if (!body) {
        (void)snprintf(err, errcap, "could not build the summary request");
        return -1;
    }
    rc = pic_stream_post(st->net, s, &st->model, st->url, PIC_AUTH_BEARER, extra, 1, body, &dec, NULL, 0, retryable, err, errcap);
    free(body);
    if (rc != 0) {
        return -1;
    }
    /* A summary cut off at the token cap is incomplete: never a checkpoint. */
    if (pic_chat_stop(&d.dec) && strcmp(pic_chat_stop(&d.dec), "length") == 0) {
        pch_dec_end(&d);
        (void)snprintf(err, errcap, "the summary hit the token cap and is incomplete");
        return -1;
    }
    neutral = pic_chat_neutral(&d.dec);
    *text = neutral ? pic_neutral_text(s->db, neutral) : NULL;
    *usage = d.dec.usage ? pic_strdup(d.dec.usage) : NULL;
    free(neutral);
    pch_dec_end(&d);
    if (!*text) {
        (void)snprintf(err, errcap, "the summary reply had no text");
        return -1;
    }
    return 0;
}

static void chat_free(pic_provider *p) {
    pch_state *st = p->state;
    if (st) {
        pic_net_free(st->net);
        free(st->url);
        free(st->workspace);
        free(st);
    }
    p->state = NULL;
}

static int chat_open(pic_provider *p, const pic_model *m, const char *url, const char *workspace, char *err,
                     size_t errcap) {
    char endpoint[512];
    pch_state *st = calloc(1, sizeof *st);
    p->reply = chat_reply;
    p->summarize = chat_summarize;
    p->context_window = m->context_window;
    p->free = chat_free;
    p->state = st;
    if (!st) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    st->model = *m;
    pic_model_url(m, endpoint, sizeof endpoint);
    if (!(st->url = pic_strdup(url ? url : endpoint)) || !(st->workspace = pic_strdup(workspace))) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    st->net = pic_net_new(err, errcap);
    return st->net ? 0 : -1;
}

/* Long retention: Anthropic's hour where the model takes cache_control (OpenRouter's anthropic/...),
 * else OpenAI's prompt_cache_retention of 24 hours. */
static long chat_cache_long(const pic_model *m) {
    return m->compat.cache_control ? 3600 : 86400;
}

/* "call|item" ids (from the responses API) become call_item, and one over 40
 * characters prefix_hash; OpenAI itself caps any id at 40. */
static void chat_norm_id(char *buf, size_t cap, const char *id, const char *provider) {
    char *bar = strchr(buf, '|');
    if (bar) {
        char hash[9];
        *bar = '_';
        pic_id_sanitize(buf);
        if (strlen(buf) > 40) {
            pic_id_hash(id, hash);
            buf[40 - 9] = '\0';
            (void)snprintf(buf + strlen(buf), cap - strlen(buf), "_%s", hash);
        }
    } else if (provider && strcmp(provider, "openai") == 0 && strlen(buf) > 40) {
        buf[40] = '\0';
    }
}

static void chat_image(sqlite3_str *out, const char *mime, const char *data) {
    sqlite3_str_appendf(out, "{\"type\":\"image_url\",\"image_url\":{\"url\":\"data:%s;base64,%s\"}}", mime, data);
}

/* chat-user: the blocks, empty text left out; chat-tool: the text joined, as
 * a string; chat-tool-images: the image parts alone, NULL when none is left
 * (they go after the run of tool results in a user message). */
static const pic_content_shape chat_shapes[] = {
    {"chat-user", PIC_SHAPE_BLOCKS, 0, 2, 0, 0, NULL, chat_image},
    {"chat-tool", PIC_SHAPE_TEXT, 1, 0, 0, 0, NULL, chat_image},
    {"chat-tool-images", PIC_SHAPE_AFTER, 1, 0, 1, 0, NULL, chat_image},
};

/* Free checks. OpenRouter's key endpoint reports what the key may still
 * spend, DeepSeek's balance endpoint what the account holds; any other
 * server's models list says the key is valid or refused. */
typedef enum { CHAT_PROBE_MODELS, CHAT_PROBE_OPENROUTER, CHAT_PROBE_DEEPSEEK } chat_probe_kind;

static chat_probe_kind chat_probe_of(const pic_model *m) {
    if (strcmp(m->provider, "openrouter") == 0 || strstr(m->base_url, "openrouter.ai")) {
        return CHAT_PROBE_OPENROUTER;
    }
    if (strcmp(m->provider, "deepseek") == 0 || strstr(m->base_url, "deepseek.com")) {
        return CHAT_PROBE_DEEPSEEK;
    }
    return CHAT_PROBE_MODELS;
}

static void chat_probe_request(const pic_model *m, pic_probe_request *req) {
    chat_probe_kind kind = chat_probe_of(m);
    (void)snprintf(req->path, sizeof req->path, "%s",
                   kind == CHAT_PROBE_OPENROUTER ? "/key" : kind == CHAT_PROBE_DEEPSEEK ? "/user/balance" : "/models");
    req->auth = PIC_AUTH_BEARER;
}

/* OpenRouter: {"data":{"limit":10,"limit_remaining":4.12,...}}; a key with no limit says null
 * and stays valid. DeepSeek: {"is_available":true,"balance_infos":[{"currency":"CNY",
 * "total_balance":"110.00"}]}; the dollar balance when there is one, else the first. */
static void chat_probe_read(const pic_model *m, const char *body, pic_key_health *h) {
    chat_probe_kind kind = chat_probe_of(m);
    char v[64], path[64];
    if (kind == CHAT_PROBE_OPENROUTER && pic_json_get(body, "$.data.limit_remaining", v, sizeof v) == 0) {
        h->remaining = strtod(v, NULL);
        h->has_remaining = 1;
        h->currency[0] = '\0';
        if (h->remaining <= 0) {
            h->state = PIC_KEY_CREDIT;
            (void)snprintf(h->reason, sizeof h->reason, "the key's spending limit is reached");
        }
    } else if (kind == CHAT_PROBE_DEEPSEEK) {
        int pick = -1;
        for (int i = 0; i < 8; i++) {
            (void)snprintf(path, sizeof path, "$.balance_infos[%d].currency", i);
            if (pic_json_get(body, path, v, sizeof v) != 0) {
                break;
            }
            if (pick < 0 || strcmp(v, "USD") == 0) {
                pick = i;
            }
        }
        if (pick >= 0) {
            (void)snprintf(path, sizeof path, "$.balance_infos[%d].currency", pick);
            (void)pic_json_get(body, path, v, sizeof v);
            (void)snprintf(h->currency, sizeof h->currency, "%s", strcmp(v, "CNY") == 0 ? "\xc2\xa5" : strcmp(v, "USD") == 0 ? "$" : v);
            (void)snprintf(path, sizeof path, "$.balance_infos[%d].total_balance", pick);
            if (pic_json_get(body, path, v, sizeof v) == 0) {
                h->remaining = strtod(v, NULL);
                h->has_remaining = 1;
            }
        }
        if (pic_json_get(body, "$.is_available", v, sizeof v) == 0 && strcmp(v, "0") == 0) {
            h->state = PIC_KEY_CREDIT;
            (void)snprintf(h->reason, sizeof h->reason, "the balance is spent");
        }
    }
}

static const pic_provider_probe chat_probe = {chat_probe_request, chat_probe_read};

const pic_provider_adapter pic_chat_adapter = {
    "openai-completions", chat_open, chat_cache_long, chat_norm_id,
    chat_shapes,  sizeof chat_shapes / sizeof chat_shapes[0], &chat_probe,
};