Skip to content
pi-c Artifact [c6f059b1df]
Login

Artifact [c6f059b1df]

Artifact c6f059b1dfbe9c4125beb23d56196646462daa7814d3d812c3323d3ff5e53b71:


/* Gemini stream decoder; see gemini.h. Finish reasons follow Pi's mapStopReason:
 * STOP is stop (toolUse once the reply has tool calls), MAX_TOKENS and
 * CONTINUATION are length, every other reason fails the stream, as does a
 * stream that ends without one. A call without an id, or with one already
 * used in the reply, gets "name_N". */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "gemini.h"

static int fail(pic_gemini *g, const char *fmt, ...) {
    va_list ap;
    if (!g->failed) {
        va_start(ap, fmt);
        (void)vsnprintf(g->err, sizeof g->err, fmt, ap);
        va_end(ap);
        g->failed = 1;
    }
    return -1;
}

static char *dup_n(const char *s, size_t n) {
    char *p = malloc(n + 1);
    if (p) {
        memcpy(p, s, n);
        p[n] = '\0';
    }
    return p;
}

/* SELECT with text arguments; *out gets column 0 as text or NULL. */
static int sql_text(pic_gemini *g, const char *sql, char **out, int nargs, ...) {
    sqlite3_stmt *st = NULL;
    va_list ap;
    int rc;
    *out = NULL;
    if (sqlite3_prepare_v2(g->db, sql, -1, &st, NULL) != SQLITE_OK) {
        return fail(g, "json: %s", sqlite3_errmsg(g->db));
    }
    va_start(ap, nargs);
    for (int i = 1; i <= nargs; i++) {
        const char *s = va_arg(ap, const char *);
        size_t n = va_arg(ap, size_t);
        if (s) {
            (void)sqlite3_bind_text(st, i, s, (int)n, SQLITE_STATIC);
        }
    }
    va_end(ap);
    rc = sqlite3_step(st);
    if (rc == SQLITE_ROW && sqlite3_column_type(st, 0) != SQLITE_NULL) {
        *out = dup_n((const char *)sqlite3_column_text(st, 0), (size_t)sqlite3_column_bytes(st, 0));
        if (!*out) {
            rc = SQLITE_NOMEM;
        }
    }
    sqlite3_finalize(st);
    if (rc != SQLITE_ROW && rc != SQLITE_DONE) {
        return fail(g, "malformed event JSON");
    }
    return 0;
}

static int keep(pic_gemini *g, char **slot, char *value) {
    size_t n = value ? strlen(value) : 0;
    if (n > PIC_GEMINI_CAP - g->total) {
        free(value);
        return fail(g, "reply exceeds %u bytes", PIC_GEMINI_CAP);
    }
    g->total += n;
    free(*slot);
    *slot = value;
    return 0;
}

int pic_gemini_init(pic_gemini *g, sqlite3 *db) {
    memset(g, 0, sizeof *g);
    g->db = db;
    g->native = sqlite3_str_new(db);
    g->neutral = sqlite3_str_new(db);
    g->text = sqlite3_str_new(db);
    g->ids = dup_n("\n", 1);
    sqlite3_str_appendall(g->native, "[");
    sqlite3_str_appendall(g->neutral, "[");
    return g->native && g->neutral && g->text && g->ids ? 0 : -1;
}

void pic_gemini_free(pic_gemini *g) {
    sqlite3_free(sqlite3_str_finish(g->native));
    sqlite3_free(sqlite3_str_finish(g->neutral));
    sqlite3_free(sqlite3_str_finish(g->text));
    free(g->sig);
    free(g->ids);
    free(g->finish_reason);
    free(g->usage);
    free(g->response_id);
    free(g->error);
    memset(g, 0, sizeof *g);
}

/* Appends one element (JSON text) to a block list. */
static int add(pic_gemini *g, sqlite3_str *list, int *n, const char *json) {
    size_t len = json ? strlen(json) : 0;
    if (!json) {
        return fail(g, "could not build a reply block");
    }
    if (len > PIC_GEMINI_CAP - g->total) {
        return fail(g, "reply exceeds %u bytes", PIC_GEMINI_CAP);
    }
    g->total += len;
    sqlite3_str_appendall(list, *n ? "," : "");
    sqlite3_str_appendall(list, json);
    (*n)++;
    return 0;
}

/* Closes the open text or thinking block into both lists. */
static int flush(pic_gemini *g) {
    char *text, *neutral = NULL, *native = NULL;
    int rc, thinking = g->kind == 2;
    if (g->kind == 0) {
        return 0;
    }
    text = sqlite3_str_finish(g->text);
    g->text = sqlite3_str_new(g->db);
    g->kind = 0;
    if (!text || !g->text) {
        sqlite3_free(text);
        return fail(g, "out of memory");
    }
    rc = sql_text(g,
                  thinking ? "SELECT json_patch(json_object('type','thinking','thinking',?1),json_object('signature',?2))"
                           : "SELECT json_patch(json_object('type','text','text',?1),json_object('textSignature',?2))",
                  &neutral, 2, text, strlen(text), g->sig, g->sig ? strlen(g->sig) : (size_t)0);
    if (rc == 0) {
        rc = sql_text(g,
                      "SELECT json_patch(json_object('text',?1),json_object('thought',CASE WHEN ?3 THEN json('true') END,"
                      "'thoughtSignature',?2))",
                      &native, 3, text, strlen(text), g->sig, g->sig ? strlen(g->sig) : (size_t)0,
                      thinking ? "1" : "0", (size_t)1);
    }
    sqlite3_free(text);
    free(g->sig);
    g->sig = NULL;
    if (rc == 0) {
        rc = add(g, g->neutral, &g->nneutral, neutral) == 0 ? add(g, g->native, &g->nnative, native) : -1;
    }
    free(neutral);
    free(native);
    return rc;
}

static int text_part(pic_gemini *g, const char *text, size_t n, int thought, const char *sig) {
    int kind = thought ? 2 : 1;
    if (g->kind != kind && (flush(g) != 0 || (g->kind = kind) == 0)) {
        return -1;
    }
    if (n > PIC_GEMINI_CAP - g->total) {
        return fail(g, "reply exceeds %u bytes", PIC_GEMINI_CAP);
    }
    g->total += n;
    sqlite3_str_append(g->text, text, (int)n);
    if (sig && *sig) {
        char *copy = dup_n(sig, strlen(sig));
        if (!copy) {
            return fail(g, "out of memory");
        }
        free(g->sig);
        g->sig = copy;
    }
    if (g->on_delta && n > 0) {
        g->on_delta(g->delta_ctx, thought, text, n);
    }
    return 0;
}

static int call_part(pic_gemini *g, const char *call, const char *name, const char *id, const char *sig) {
    char *neutral = NULL, *native = NULL, made[300], *grown;
    const char *use = id && *id ? id : NULL;
    size_t n;
    int rc;
    if (flush(g) != 0) {
        return -1;
    }
    g->calls++;
    if (use) { /* already used in this reply? */
        char needle[300];
        (void)snprintf(needle, sizeof needle, "\n%.250s\n", use);
        if (strstr(g->ids, needle)) {
            use = NULL;
        }
    }
    for (int k = g->calls; !use; k++) {
        char needle[300];
        (void)snprintf(made, sizeof made, "%.200s_%d", name ? name : "", k);
        (void)snprintf(needle, sizeof needle, "\n%s\n", made);
        if (!strstr(g->ids, needle)) {
            use = made;
        }
    }
    n = strlen(g->ids) + strlen(use) + 2;
    grown = realloc(g->ids, n);
    if (!grown) {
        return fail(g, "out of memory");
    }
    g->ids = grown;
    (void)snprintf(g->ids + strlen(g->ids), n - strlen(g->ids), "%s\n", use);
    rc = sql_text(g,
                  "SELECT json_patch(json_object('type','toolCall','id',?1,'name',coalesce(?2,''),'arguments',"
                  "json(CASE WHEN json_type(?3,'$.args')='object' THEN json_extract(?3,'$.args') ELSE '{}' END)),"
                  "json_object('thoughtSignature',?4))",
                  &neutral, 4, use, strlen(use), name, name ? strlen(name) : (size_t)0, call, strlen(call), sig,
                  sig ? strlen(sig) : (size_t)0);
    if (rc == 0) {
        rc = sql_text(g, "SELECT json_patch(json_object('functionCall',json(?1)),json_object('thoughtSignature',?2))",
                      &native, 2, call, strlen(call), sig, sig ? strlen(sig) : (size_t)0);
    }
    if (rc == 0) {
        rc = add(g, g->neutral, &g->nneutral, neutral) == 0 ? add(g, g->native, &g->nnative, native) : -1;
    }
    free(neutral);
    free(native);
    return rc;
}

/* The parts of a response: text (thought or not) and function calls. */
static int parts(pic_gemini *g, const char *data, size_t len) {
    sqlite3_stmt *q = NULL;
    int step, rc = 0;
    if (sqlite3_prepare_v2(g->db,
                           "SELECT json_type(p.value,'$.text'), json_extract(p.value,'$.text'),"
                           " coalesce(json_extract(p.value,'$.thought') = 1, 0), json_extract(p.value,'$.thoughtSignature'),"
                           " json_type(p.value,'$.functionCall'), json_extract(p.value,'$.functionCall'),"
                           " json_extract(p.value,'$.functionCall.name'), json_extract(p.value,'$.functionCall.id')"
                           " FROM json_each(?1,'$.candidates[0].content.parts') p ORDER BY p.key",
                           -1, &q, NULL) != SQLITE_OK) {
        return fail(g, "json: %s", sqlite3_errmsg(g->db));
    }
    sqlite3_bind_text(q, 1, data, (int)len, SQLITE_STATIC);
    while (rc == 0 && (step = sqlite3_step(q)) == SQLITE_ROW) {
        const char *sig = (const char *)sqlite3_column_text(q, 3);
        if (sqlite3_column_text(q, 0) && strcmp((const char *)sqlite3_column_text(q, 0), "text") == 0) {
            rc = text_part(g, (const char *)sqlite3_column_text(q, 1), (size_t)sqlite3_column_bytes(q, 1),
                           sqlite3_column_int(q, 2), sig);
        }
        if (rc == 0 && sqlite3_column_text(q, 4) && strcmp((const char *)sqlite3_column_text(q, 4), "object") == 0) {
            rc = call_part(g, (const char *)sqlite3_column_text(q, 5), (const char *)sqlite3_column_text(q, 6),
                           (const char *)sqlite3_column_text(q, 7), sig);
        }
    }
    if (rc == 0 && step != SQLITE_DONE) {
        rc = fail(g, "malformed event JSON");
    }
    sqlite3_finalize(q);
    return rc;
}

int pic_gemini_event(void *ctx, const char *event, const char *data, size_t len) {
    pic_gemini *g = ctx;
    char *s = NULL;
    (void)event;
    if (g->failed) {
        return -1;
    }
    if (sql_text(g, "SELECT CASE WHEN json_valid(?1) AND json_type(?1)='object' THEN 'ok' END", &s, 1, data, len) != 0) {
        return -1;
    }
    if (!s) {
        return fail(g, "an event that is not a JSON object");
    }
    free(s);
    if (sql_text(g,
                 "SELECT CASE WHEN json_type(?1,'$.error')='object' THEN coalesce(json_extract(?1,'$.error.message'),"
                 " json_extract(?1,'$.error.status'), 'error') END",
                 &s, 1, data, len) != 0) {
        return -1;
    }
    if (s) {
        return keep(g, &g->error, s);
    }
    if (sql_text(g, "SELECT 'prompt blocked: ' || json_extract(?1,'$.promptFeedback.blockReason')", &s, 1, data, len) != 0 ||
        keep(g, &g->error, s) != 0) {
        return -1;
    }
    if (!g->response_id) {
        if (sql_text(g, "SELECT nullif(json_extract(?1,'$.responseId'),'')", &s, 1, data, len) != 0 ||
            keep(g, &g->response_id, s) != 0) {
            return -1;
        }
    }
    if (parts(g, data, len) != 0) {
        return -1;
    }
    if (sql_text(g, "SELECT json_extract(?1,'$.candidates[0].finishReason')", &s, 1, data, len) != 0) {
        return -1;
    }
    if (s) {
        if (keep(g, &g->finish_reason, s) != 0) {
            return -1;
        }
    }
    /* Pi's usage: input is the prompt less cached tokens, output adds the
     * thinking tokens. */
    if (sql_text(g,
                 "SELECT CASE json_type(?1,'$.usageMetadata') WHEN 'object' THEN json_object("
                 "'input_tokens', coalesce(json_extract(?1,'$.usageMetadata.promptTokenCount'),0)"
                 "   - coalesce(json_extract(?1,'$.usageMetadata.cachedContentTokenCount'),0),"
                 "'output_tokens', coalesce(json_extract(?1,'$.usageMetadata.candidatesTokenCount'),0)"
                 "   + coalesce(json_extract(?1,'$.usageMetadata.thoughtsTokenCount'),0),"
                 "'cache_read_input_tokens', coalesce(json_extract(?1,'$.usageMetadata.cachedContentTokenCount'),0),"
                 "'reasoning_tokens', coalesce(json_extract(?1,'$.usageMetadata.thoughtsTokenCount'),0),"
                 "'total_tokens', coalesce(json_extract(?1,'$.usageMetadata.totalTokenCount'),0)) END",
                 &s, 1, data, len) != 0) {
        return -1;
    }
    if (s) {
        return keep(g, &g->usage, s);
    }
    return 0;
}

int pic_gemini_finish(pic_gemini *g) {
    const char *why = g->finish_reason;
    if (g->failed) {
        return -1;
    }
    if (g->error) {
        return fail(g, "%.200s", g->error);
    }
    if (!why) {
        return fail(g, "stream ended without a finish reason");
    }
    if (strcmp(why, "STOP") != 0 && strcmp(why, "MAX_TOKENS") != 0 && strcmp(why, "CONTINUATION") != 0) {
        return fail(g, "Provider stopped with: %.60s", why);
    }
    if (!g->flushed) {
        if (flush(g) != 0) {
            return -1;
        }
        g->flushed = 1;
    }
    return 0;
}

/* The list so far, closed (the list itself stays open). */
static char *list_text(sqlite3_str *list) {
    const char *t = sqlite3_str_value(list);
    size_t n = t ? strlen(t) : 0;
    char *res = t ? malloc(n + 2) : NULL;
    if (res) {
        memcpy(res, t, n);
        res[n] = ']';
        res[n + 1] = '\0';
    }
    return res;
}

char *pic_gemini_native(pic_gemini *g) { return list_text(g->native); }

char *pic_gemini_neutral(pic_gemini *g) { return list_text(g->neutral); }

const char *pic_gemini_stop(const pic_gemini *g) {
    if (g->finish_reason && strcmp(g->finish_reason, "STOP") != 0) {
        return "length";
    }
    return g->calls > 0 ? "toolUse" : "stop";
}