Artifact 87bd429b30f949d1e187e9626fb8238e98cb9487a561ec99dd1e7d2eb8365436:
- File
src/provider_http.c
— part of check-in
[376fd483ed]
at
2026-11-20 00:29:28
on branch cache
— Prompt caching on every provider, as Pi's
Anthropic: cache_control on the system block, the last tool and the last block of the final user message; 5 minutes by default, ttl 1h with cacheRetention=long, none with cacheRetention=none (setting in pic.sqlite, PI_CACHE_RETENTION as fallback). Anthropic models through OpenRouter get the same markers. OpenAI Responses and Chat Completions send prompt_cache_key (the conversation id) and 24h retention when long, as Pi does. The system prompt and tools stay byte-identical across turns, and 1-hour cache writes are kept in the stored usage. (user: dmestas, size: 10446) [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 <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "cred.h" #include "userdb.h" #include "net.h" #include "platform.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); } /* Waits ms, serving the side descriptor meanwhile; Ctrl-C ends the wait. */ static void pause_ms(long ms) { uint64_t end = pic_platform_get()->mono_ns() + (uint64_t)ms * 1000000u; for (uint64_t now; !pic_interrupted && (now = pic_platform_get()->mono_ns()) < end;) { long left = (long)((end - now) / 1000000u) + 1; if (pic_side_fd >= 0 && pic_side_ready) { pic_side_poll((int)(left < 1000 ? left : 1000)); } else { struct timespec ts = {left / 1000, (left % 1000) * 1000000L}; (void)nanosleep(&ts, NULL); } } } /* 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" : "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; } pic_cache pic_cache_retention(void) { char *v = pic_setting("cacheRetention"); const char *env = getenv("PI_CACHE_RETENTION"); pic_cache r = PIC_CACHE_SHORT; if (v && strcmp(v, "long") == 0) { r = PIC_CACHE_LONG; } else if (v && strcmp(v, "none") == 0) { r = PIC_CACHE_NONE; } else if (!(v && strcmp(v, "short") == 0) && env && strcmp(env, "long") == 0) { r = PIC_CACHE_LONG; } free(v); return r; } const char *pic_cache_control(pic_cache retention, int long_ok) { return retention == PIC_CACHE_NONE ? NULL : retention == PIC_CACHE_LONG && long_ok ? "{\"type\":\"ephemeral\",\"ttl\":\"1h\"}" : "{\"type\":\"ephemeral\"}"; } char *pic_session_id(pic_store *s, int64_t submission) { sqlite3_stmt *q = NULL; char *out = NULL; if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) != SQLITE_OK) { return NULL; } sqlite3_bind_int64(q, 1, submission); 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; } 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); 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; }