Skip to content
pi-c Documentation
Login

Documentation

/* Gemini adapter (google-generative-ai): the request built from the journal as
 * Pi's adapter builds it, streamed through the shared POST and the response
 * decoder. Replies are rebuilt from their neutral form for every target, as
 * Pi does: the model that made a reply gets its thinking and thought
 * signatures back (valid base64 only), any other gets text and tool calls,
 * its thinking dropped as everywhere in pic (transform.c). */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "gemini.h"
#include "provider_http.h"

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

/* Pi's getGeminiMajorVersion: N of "gemini-N..." or "gemini-live-N...", else 0. */
static int major_version(const char *id) {
    const char *p = strncmp(id, "gemini-live-", 12) == 0 ? id + 12 : strncmp(id, "gemini-", 7) == 0 ? id + 7 : NULL;
    return p && isdigit((unsigned char)*p) ? atoi(p) : 0;
}

/* Pi's requiresToolCallId: ids travel in function calls and responses. */
static int requires_id(const char *id) {
    return strncmp(id, "claude-", 7) == 0 || strncmp(id, "gpt-oss-", 8) == 0 || major_version(id) >= 3;
}

/* Pi's usesGoogleThinkingLevel: discrete levels rather than a token budget. */
static int uses_level(const char *model) {
    char id[192];
    size_t i;
    (void)snprintf(id, sizeof id, "%s", model);
    for (i = 0; id[i]; i++) {
        id[i] = (char)tolower((unsigned char)id[i]);
    }
    if (strcmp(id, "gemini-flash-latest") == 0 || strcmp(id, "gemini-flash-lite-latest") == 0 ||
        strstr(id, "gemma-4") || strstr(id, "gemma4")) {
        return 1;
    }
    for (const char *p = id; (p = strstr(p, "gemini-")) != NULL; p++) {
        const char *q = p + 7;
        if (*q == '3') { /* gemini-3[.N]-pro or -flash */
            q++;
            if (*q == '.') {
                q++;
                while (isdigit((unsigned char)*q)) {
                    q++;
                }
            }
            if (strncmp(q, "-pro", 4) == 0 || strncmp(q, "-flash", 6) == 0) {
                return 1;
            }
        } else if ((*q >= '4' && *q <= '9') || (*q >= '1' && *q <= '9' && isdigit((unsigned char)q[1]))) {
            return 1; /* gemini-4 and later */
        }
    }
    return 0;
}

/* Pi's getGoogleBudget for token-budget models; -1 is dynamic. */
static long budget(const char *model, const char *level) {
    int i = strcmp(level, "minimal") == 0 ? 0 : strcmp(level, "low") == 0 ? 1 : strcmp(level, "medium") == 0 ? 2 : 3;
    static const long pro[] = {128, 2048, 8192, 32768}, lite[] = {512, 2048, 8192, 24576}, flash[] = {128, 2048, 8192, 24576};
    return strstr(model, "2.5-pro") ? pro[i] : strstr(model, "2.5-flash-lite") ? lite[i] : strstr(model, "2.5-flash") ? flash[i] : -1;
}

/* The thinkingConfig of a request at LEVEL as JSON ("" when none), as Pi's
 * streamSimple builds it: nothing for a model without reasoning; off is a
 * zero budget; otherwise thoughts are included, with a level or a budget. */
static void thinking_config(const pic_model *m, const char *level, char *out, size_t cap) {
    const char *mapped = NULL, *name = level;
    out[0] = '\0';
    if (!m->reasoning) {
        return;
    }
    if (strcmp(level, "off") == 0) {
        (void)snprintf(out, cap, "{\"thinkingBudget\":0}");
        return;
    }
    if (pic_model_thinking_map(m, level, &mapped) == 2) {
        name = mapped;
    }
    /* Only minimal, low, medium and high go on the wire; xhigh and max (and
     * anything else) are high. */
    if (strcasecmp(name, "minimal") != 0 && strcasecmp(name, "low") != 0 && strcasecmp(name, "medium") != 0) {
        name = "high";
    }
    if (uses_level(m->id)) {
        char up[16];
        size_t i;
        for (i = 0; name[i] && i + 1 < sizeof up; i++) {
            up[i] = (char)toupper((unsigned char)name[i]);
        }
        up[i] = '\0';
        (void)snprintf(out, cap, "{\"includeThoughts\":true,\"thinkingLevel\":\"%s\"}", up);
    } else {
        char lower[16];
        size_t i;
        for (i = 0; name[i] && i + 1 < sizeof lower; i++) {
            lower[i] = (char)tolower((unsigned char)name[i]);
        }
        lower[i] = '\0';
        (void)snprintf(out, cap, "{\"includeThoughts\":true,\"thinkingBudget\":%ld}", budget(m->id, lower));
    }
}

/* The contents array: the user's text; each assistant turn rebuilt from its
 * neutral form; each run of tool results (and instruction updates) as one
 * user turn, ids normalised exactly as their calls were. */
static char *build_contents(pic_store *s, const state *st, int64_t submission, char *err, size_t errcap) {
    sqlite3_stmt *q = NULL;
    sqlite3_str *out = sqlite3_str_new(s->db);
    int in_results = 0, first = 1, step;
    if (sqlite3_prepare_v2(
            s->db,
            PIC_CONTEXT_CTE "SELECT e.kind, CASE e.kind"
            " WHEN 'user' THEN json_object('role','user','parts',json_array(json_object('text',e.body)))"
            " WHEN 'compaction' THEN json_object('role','user','parts',json_array(json_object('text',"
            PIC_SUMMARY_SQL("e.body") ")))"
            " WHEN 'branch_summary' THEN json_object('role','user','parts',json_array(json_object('text',"
            PIC_BRANCH_SUMMARY_SQL("e.body") ")))"
            " WHEN 'instructions' THEN json_object('text',"
            "   '<project_instructions_update>' || char(10) || e.body || char(10) || '</project_instructions_update>')"
            " WHEN 'tool_result' THEN json_object('functionResponse',json_patch(json_object('name',f.tool,'response',"
            "   json_object(iif(f.is_error,'error','output'),e.body)),json_object('id',CASE WHEN ?5 THEN"
            "   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,'google-generative-ai',?2) END END)))"
            " ELSE (SELECT CASE WHEN count(y) = 0 THEN NULL ELSE json_object('role','model','parts',"
            "   json_group_array(json(y)) FILTER (WHERE y IS NOT NULL)) END FROM (SELECT CASE t"
            "     WHEN 'text' THEN CASE WHEN trim(tx, ' ' || char(9,10,13)) = '' AND sig IS NULL THEN NULL"
            "       ELSE json_patch(json_object('text',tx),json_object('thoughtSignature',sig)) END"
            "     WHEN 'thinking' THEN CASE WHEN same AND NOT (trim(th, ' ' || char(9,10,13)) = '' AND sig IS NULL)"
            "       THEN json_patch(json_object('thought',json('true'),'text',th),json_object('thoughtSignature',sig))"
            "       END"
            "     WHEN 'toolCall' THEN json_patch(json_object('functionCall',json_patch(json_object('name',nm,'args',json(args)),"
            "       json_object('id',CASE WHEN ?5 THEN CASE WHEN same THEN cid ELSE pic_norm_id(cid,'google-generative-ai',?2) END END))),"
            "       json_object('thoughtSignature',sig))"
            "     END AS y FROM (SELECT json_extract(b.value,'$.type') AS t, json_extract(b.value,'$.text') AS tx,"
            "       json_extract(b.value,'$.thinking') AS th, json_extract(b.value,'$.name') AS nm,"
            "       json_extract(b.value,'$.arguments') AS args, json_extract(b.value,'$.id') AS cid, same,"
            "       CASE WHEN same AND sg IS NOT NULL AND sg != '' AND length(sg) % 4 = 0"
            "         AND sg NOT GLOB '*[^A-Za-z0-9+/=]*' THEN sg END AS sig, b.key AS k"
            "       FROM (SELECT b.value AS value, b.key AS key, coalesce(json_extract(b.value,'$.textSignature'),"
            "         json_extract(b.value,'$.signature'),json_extract(b.value,'$.thoughtSignature')) AS sg,"
            "         (v.fresh AND e.provider IS ?2 AND e.api IS ?3 AND e.model IS ?4) AS same FROM json_each(e.body) b) b)"
            "     ORDER BY k)) END 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));
        return NULL;
    }
    sqlite3_bind_int64(q, 1, submission);
    sqlite3_bind_text(q, 2, st->model.provider, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, pic_api_name(st->model.api), -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 4, st->model.id, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 5, requires_id(st->model.id));
    sqlite3_str_appendall(out, "[");
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        /* Tool results and instruction updates are parts of one user turn. */
        const char *kind = (const char *)sqlite3_column_text(q, 0);
        int result = strcmp(kind, "tool_result") == 0 || strcmp(kind, "instructions") == 0;
        const char *item = (const char *)sqlite3_column_text(q, 1);
        if (!item) {
            continue; /* a foreign turn with nothing this API can take */
        }
        if (in_results && !result) {
            sqlite3_str_appendall(out, "]}");
            in_results = 0;
        }
        if (result && in_results) {
            sqlite3_str_appendall(out, ",");
        } else {
            sqlite3_str_appendall(out, first ? "" : ",");
            if (result) {
                sqlite3_str_appendall(out, "{\"role\":\"user\",\"parts\":[");
                in_results = 1;
            }
        }
        sqlite3_str_appendall(out, item);
        first = 0;
    }
    sqlite3_finalize(q);
    if (in_results) {
        sqlite3_str_appendall(out, "]}");
    }
    sqlite3_str_appendall(out, "]");
    if (step != SQLITE_DONE || sqlite3_str_errcode(out) != SQLITE_OK) {
        (void)snprintf(err, errcap, "could not build the request");
        sqlite3_free(sqlite3_str_finish(out));
        return NULL;
    }
    return sqlite3_str_finish(out);
}

static char *build_body(pic_store *s, const state *st, const char *level, int64_t submission, const char *contents) {
    char thinking[160];
    sqlite3_stmt *q = NULL;
    char *body = NULL, *system_prompt = pic_session_text(s, submission, "system_prompt"),
         *tools = pic_session_text(s, submission, "tools");
    thinking_config(&st->model, level, thinking, sizeof thinking);
    if (!system_prompt || !tools) {
        free(system_prompt);
        free(tools);
        return NULL;
    }
    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_object('contents',json(?1),'systemInstruction',json_object('parts',json_array(json_object('text',?2))),"
            "'tools',json_array(json_object('functionDeclarations',json((SELECT json_group_array(json_object('name',"
            "json_extract(value,'$.name'),'description',json_extract(value,'$.description'),'parametersJsonSchema',"
            "json(json_extract(value,'$.input_schema')))) FROM json_each(?3))))),"
            "'generationConfig',json_patch(json_object('maxOutputTokens',?4),json_object('thinkingConfig',json(nullif(?5,''))))) AS b)",
            -1, &q, NULL) != SQLITE_OK) {
        free(system_prompt);
        free(tools);
        return NULL;
    }
    sqlite3_bind_text(q, 1, contents, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, system_prompt, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, tools, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 4, st->model.max_tokens);
    sqlite3_bind_text(q, 5, thinking, -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);
    free(system_prompt);
    free(tools);
    return body;
}

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

static int dec_begin(void *ctx) {
    decoding *d = ctx;
    if (pic_gemini_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 dec_event(void *ctx, const char *event, const char *data, size_t len) {
    return pic_gemini_event(&((decoding *)ctx)->dec, event, data, len);
}

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

static void dec_end(void *ctx) { pic_gemini_free(&((decoding *)ctx)->dec); }

static int gemini_reply(pic_provider *p, pic_store *s, int64_t submission, int64_t turn, pic_reply *out, int *retryable,
                        char *err, size_t errcap) {
    state *st = p->state;
    static const char *const extra[] = {"Accept: text/event-stream"};
    decoding d;
    pic_stream_decoder dec = {dec_begin, dec_event, dec_finish, dec_end, &d};
    char *contents, *body, request_id[128];
    int rc;
    (void)turn;
    *retryable = 0;
    memset(out, 0, sizeof *out);
    memset(&d, 0, sizeof d);
    d.db = s->db;
    d.stream = s;
    contents = build_contents(s, st, submission, err, errcap);
    body = contents ? build_body(s, st, p->thinking, submission, contents) : NULL;
    sqlite3_free(contents);
    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_X_GOOG_API_KEY, extra, 1, body, &dec, request_id,
                         sizeof request_id, retryable, err, errcap);
    free(body);
    if (rc != 0) {
        return -1;
    }
    out->native = pic_gemini_native(&d.dec);
    out->neutral = pic_gemini_neutral(&d.dec);
    out->stop_reason = pic_strdup(pic_gemini_stop(&d.dec));
    out->usage = d.dec.usage ? pic_strdup(d.dec.usage) : NULL;
    out->request_id = request_id[0] ? pic_strdup(request_id) : d.dec.response_id ? pic_strdup(d.dec.response_id) : NULL;
    out->provider = pic_strdup(st->model.provider);
    out->api = pic_strdup(pic_api_name(st->model.api));
    out->model = pic_strdup(st->model.id);
    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 gemini_summarize(pic_provider *p, pic_store *s, const char *system, const char *user, char **text, char **usage,
                            int *retryable, char *err, size_t errcap) {
    state *st = p->state;
    static const char *const extra[] = {"Accept: text/event-stream"};
    decoding d;
    pic_stream_decoder dec = {dec_begin, dec_event, dec_finish, dec_end, &d};
    char *body, *neutral, max_tokens[24];
    int rc;
    *text = *usage = NULL;
    memset(&d, 0, sizeof d);
    d.db = s->db;
    (void)snprintf(max_tokens, sizeof max_tokens, "%ld", st->model.max_tokens);
    body = pic_json_body(s->db,
                         "SELECT json_object('contents',json_array(json_object('role','user','parts',json_array("
                         "json_object('text',?2)))),'systemInstruction',json_object('parts',json_array(json_object('text',?1))),"
                         "'generationConfig',json_object('maxOutputTokens',CAST(?3 AS INTEGER)))",
                         3, system, user, max_tokens);
    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_X_GOOG_API_KEY, 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 (strcmp(pic_gemini_stop(&d.dec), "length") == 0) {
        dec_end(&d);
        (void)snprintf(err, errcap, "the summary hit the token cap and is incomplete");
        return -1;
    }
    neutral = pic_gemini_neutral(&d.dec);
    *text = neutral ? pic_neutral_text(s->db, neutral) : NULL;
    *usage = d.dec.usage ? pic_strdup(d.dec.usage) : NULL;
    free(neutral);
    dec_end(&d);
    if (!*text) {
        (void)snprintf(err, errcap, "the summary reply had no text");
        return -1;
    }
    return 0;
}

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

int pic_provider_gemini_new(pic_provider *p, const pic_model *m, const char *url, const char *workspace, char *err,
                            size_t errcap) {
    char endpoint[512];
    state *st = calloc(1, sizeof *st);
    p->reply = gemini_reply;
    p->summarize = gemini_summarize;
    p->context_window = m->context_window;
    p->free = gemini_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;
}