Artifact cd21de3ac1f03ec3116ebea1ed322d8c820d9f3f13554cfeec533b1b75363549:
- File
src/provider_http.c
— part of check-in
[1011fc8472]
at
2026-11-19 23:29:07
on branch gemini
— A Google Gemini provider, as Pi's
The google-generative-ai API: streamGenerateContent over SSE with GEMINI_API_KEY, native parts replayed per conversation, tool calls and results, usage, and Pi's thinking mapping (thinkingLevel for Gemini 3 and later, a token budget for 2.5, 0 for off). A conversation can move between Gemini and the other providers turn by turn. Recorded streams cover text, thinking, tools, parallel calls, safety blocks, truncation and errors. (user: dmestas, size: 8995) [annotate] [blame] [check-ins using]
/* The streaming POST every adapter uses, and the choice of adapter for a * model. See provider_http.h for the retry rules. */ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "cred.h" #include "http.h" #include "provider_http.h" #define HTTP_TRIES 4 #define IDLE_SECONDS 120 /* a stream may pause while the model thinks */ #define DEADLINE_SECONDS 900 /* one whole request */ #define ERROR_BODY_CAP 8192 #define KEY_CAP 512 #define MAX_HEADERS 32 char *pic_strdup(const char *s) { size_t n = strlen(s) + 1; char *p = malloc(n); if (p) { memcpy(p, s, n); } return p; } typedef struct { pic_http_resp *resp; pic_sse *sse; char error_body[ERROR_BODY_CAP]; size_t error_len; int stream_failed; } sink; static int on_body(void *ctx, const char *bytes, size_t n) { sink *k = ctx; if (k->resp->status == 200) { int rc = pic_sse_feed(k->sse, bytes, n); if (rc != 0) { k->stream_failed = 1; } return rc; } if (n > sizeof k->error_body - 1 - k->error_len) { n = sizeof k->error_body - 1 - k->error_len; } memcpy(k->error_body + k->error_len, bytes, n); k->error_len += n; k->error_body[k->error_len] = '\0'; return 0; } /* error.message from an error body (both APIs nest it there), or the status. */ static void error_text(pic_store *s, int status, const char *body, char *err, size_t errcap) { sqlite3_stmt *q = NULL; const char *msg = NULL; if (sqlite3_prepare_v2(s->db, "SELECT CASE WHEN json_valid(?1) THEN coalesce(json_extract(?1,'$.error.message')," " json_extract(?1,'$.message')) END", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, body, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { msg = (const char *)sqlite3_column_text(q, 0); } } (void)snprintf(err, errcap, "HTTP %d%s%.300s", status, msg ? ": " : "", msg ? msg : ""); sqlite3_finalize(q); } static void pause_ms(long ms) { struct timespec ts; ts.tv_sec = ms / 1000; ts.tv_nsec = (ms % 1000) * 1000000L; while (nanosleep(&ts, &ts) != 0 && !pic_interrupted) { } } /* Milliseconds to wait before try number `tryno` (1-based) after a failure. */ static long backoff_ms(const pic_http_resp *r, int tryno) { long ms = 500L << (tryno - 1); if (r && r->retry_after[0]) { char *end; long secs = strtol(r->retry_after, &end, 10); if (*end == '\0' && secs >= 0) { ms = secs * 1000; } } return ms > 30000 ? 30000 : ms; } int pic_stream_post(pic_net *net, pic_store *s, const pic_model *m, const char *url, pic_auth_style auth, const char *const *extra, size_t nextra, const char *body, const pic_stream_decoder *dec, char *request_id, size_t request_id_cap, int *retryable, char *err, size_t errcap) { char key[KEY_CAP], auth_line[KEY_CAP + 32], model_headers[sizeof m->headers]; const char *headers[MAX_HEADERS]; size_t nheaders = 0; int keyed, rc = -1; *retryable = 0; if (request_id_cap) { request_id[0] = '\0'; } keyed = pic_cred_get(m->key_env, m->key_literal, key, sizeof key, err, errcap); if (keyed < 0) { return -1; } auth_line[0] = '\0'; if (keyed == 0) { (void)snprintf(auth_line, sizeof auth_line, auth == PIC_AUTH_BEARER ? "Authorization: Bearer %s" : auth == PIC_AUTH_X_GOOG_API_KEY ? "x-goog-api-key: %s" : "x-api-key: %s", key); headers[nheaders++] = auth_line; } pic_cred_wipe(key, sizeof key); for (size_t i = 0; i < nextra && nheaders < MAX_HEADERS; i++) { headers[nheaders++] = extra[i]; } /* Headers from the models file, one per line. */ (void)snprintf(model_headers, sizeof model_headers, "%s", m->headers); for (char *line = model_headers; *line && nheaders < MAX_HEADERS;) { char *nl = strchr(line, '\n'); if (nl) { *nl = '\0'; } headers[nheaders++] = line; if (!nl) { break; } line = nl + 1; } for (int tryno = 1; tryno <= HTTP_TRIES; tryno++) { pic_http_resp resp; pic_sse sse; sink k; int post, transient; memset(&k, 0, sizeof k); if (dec->begin(dec->ctx) != 0 || pic_sse_init(&sse, 1u << 20, 16u << 20, dec->event, dec->ctx) != 0) { dec->end(dec->ctx); (void)snprintf(err, errcap, "out of memory"); break; } k.resp = &resp; k.sse = &sse; pic_http_resp_init(&resp, on_body, &k); post = pic_http_post(net, url, headers, nheaders, body, strlen(body), &resp, IDLE_SECONDS, DEADLINE_SECONDS, err, errcap); pic_fault("after-response"); if (resp.status == 200) { char why[320] = ""; int complete = post == 0 && !k.stream_failed && pic_sse_pending(&sse) == 0 && dec->finish(dec->ctx, why, sizeof why) == 0; pic_sse_free(&sse); if (complete) { if (request_id_cap) { (void)snprintf(request_id, request_id_cap, "%s", resp.request_id); } rc = 0; break; /* the decoder stays live for the adapter */ } /* The stream broke after it began: no retry here. */ if (!why[0]) { (void)snprintf(why, sizeof why, "%s", post != 0 ? err : "incomplete stream"); } dec->end(dec->ctx); *retryable = 1; (void)snprintf(err, errcap, "stream failed: %.300s", why); break; } pic_sse_free(&sse); dec->end(dec->ctx); transient = post != 0 ? !pic_net_tls_failed(net) : resp.status == 429 || resp.status == 529 || resp.status >= 500; if (post == 0) { error_text(s, resp.status, k.error_body, err, errcap); } if (!transient) { break; } *retryable = 1; if (tryno < HTTP_TRIES) { pause_ms(backoff_ms(post == 0 ? &resp : NULL, tryno)); } } pic_cred_wipe(auth_line, sizeof auth_line); if (rc == 0) { *retryable = 0; } return rc; } int pic_provider_for_model(pic_provider *p, const pic_model *model, const char *thinking, const char *url, const char *workspace, char *err, size_t errcap) { (void)snprintf(p->model, sizeof p->model, "%s/%s", model->provider, model->id); (void)snprintf(p->thinking, sizeof p->thinking, "%s", pic_model_thinking_clamp(model, thinking && *thinking ? thinking : "medium")); switch (model->api) { case PIC_API_ANTHROPIC: return pic_provider_anthropic_new(p, model, url, workspace, err, errcap); case PIC_API_CHAT: return pic_provider_chat_new(p, model, url, workspace, err, errcap); case PIC_API_RESPONSES: return pic_provider_responses_new(p, model, url, workspace, err, errcap); case PIC_API_GEMINI: return pic_provider_gemini_new(p, model, url, workspace, err, errcap); default: (void)snprintf(err, errcap, "%s models are not supported yet (provider %s)", pic_api_name(model->api), model->provider); return -1; } } /* The text blocks of a neutral content array, joined (malloc'd). */ char *pic_neutral_text(sqlite3 *db, const char *neutral) { sqlite3_stmt *q = NULL; char *out = NULL; if (sqlite3_prepare_v2(db, "SELECT coalesce(group_concat(json_extract(value,'$.text'), char(10)), '') FROM json_each(?1)" " WHERE json_extract(value,'$.type') = 'text'", -1, &q, NULL) != SQLITE_OK) { return NULL; } sqlite3_bind_text(q, 1, neutral, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW) { out = pic_strdup((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); return out; } /* A request body built by one SQL statement with text parameters. */ char *pic_json_body(sqlite3 *db, const char *sql, int nargs, ...) { sqlite3_stmt *q = NULL; char *out = NULL; va_list ap; if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) != SQLITE_OK) { return NULL; } va_start(ap, nargs); for (int i = 1; i <= nargs; i++) { sqlite3_bind_text(q, i, va_arg(ap, const char *), -1, SQLITE_TRANSIENT); } va_end(ap); if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) { out = pic_strdup((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); return out; }