Skip to content
pi-c Artifact [22c7a18656]
Login

Artifact [22c7a18656]

Artifact 22c7a18656f8c11b20849439846274843986c74a27f906fd5c683240d308ee97:


/* Gemini streamGenerateContent decoder: SSE events in, one reply out, as the
 * model's parts (native) and as Pi's neutral content, following Pi's
 * google-generative-ai adapter. Each event is a whole GenerateContentResponse;
 * the parts of the first candidate are folded into blocks as Pi folds them:
 * consecutive text parts (thought or not) extend one block, a thought
 * signature is kept as the last non-empty one the block saw, and every
 * functionCall is a tool call of its own. Neutral blocks carry Pi's field
 * names: textSignature on text, signature on thinking, thoughtSignature on
 * toolCall. Usage is reported in the field names pic's loop reads. */
#ifndef PIC_GEMINI_H
#define PIC_GEMINI_H

#include <stddef.h>

#include "sqlite3.h"

#define PIC_GEMINI_CAP (16u << 20) /* bound on one reply */

typedef struct {
    sqlite3 *db;
    sqlite3_str *native, *neutral; /* "[" element "," element ... (no closing bracket yet) */
    int nnative, nneutral;         /* elements so far */
    int kind;                      /* open block: 0 none, 1 text, 2 thinking */
    sqlite3_str *text;             /* text of the open block */
    char *sig;                     /* last non-empty thoughtSignature of the open block */
    int calls;                     /* tool calls so far */
    char *ids;                     /* call ids so far, '\n' separated and ended */
    char *finish_reason;           /* candidates[0].finishReason */
    char *usage;                   /* JSON, in input_tokens ... names */
    char *response_id;
    char *error;                   /* an error event, or a blocked prompt */
    size_t total;
    int failed, flushed;
    char err[256];
    /* Optional: each text or thinking delta as it arrives (set after init). */
    void (*on_delta)(void *ctx, int thinking, const char *text, size_t len);
    void *delta_ctx;
} pic_gemini;

int pic_gemini_init(pic_gemini *g, sqlite3 *db);
void pic_gemini_free(pic_gemini *g);
/* Fits pic_sse_event_fn with ctx = the decoder. 0, or -1 with g->err set. */
int pic_gemini_event(void *ctx, const char *event, const char *data, size_t len);
/* End of stream: 0 when a complete reply arrived (STOP, or a length stop),
 * else -1 with g->err. */
int pic_gemini_finish(pic_gemini *g);
/* After a successful finish (malloc'd): the parts as a JSON array; */
char *pic_gemini_native(pic_gemini *g);
/* Pi's neutral content array; */
char *pic_gemini_neutral(pic_gemini *g);
/* Pi's stop reason: stop, toolUse, length. */
const char *pic_gemini_stop(const pic_gemini *g);

#endif