Skip to content
pi-c Documentation
Login

Documentation

/* 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 "events.h"
#include "net.h"
#include "userdb.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 */

/* IDLE_SECONDS, or PIC_IDLE_SECONDS when it is a positive number (tests). */
static int idle_seconds(void) {
    const char *v = getenv("PIC_IDLE_SECONDS");
    int n = v ? atoi(v) : 0;
    return n > 0 ? n : IDLE_SECONDS;
}
#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 (or Pi's
 * abort_retry) ends the wait. */
static void pause_ms(const pic_store *s, long ms) {
    uint64_t end = pic_platform_get()->mono_ns() + (uint64_t)ms * 1000000u;
    for (uint64_t now; !pic_interrupted && !(s && s->abort_retry) && (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;
}

/* A request's headers: the key in AUTH's style (into auth_line, which the
 * caller wipes), EXTRA, then the model's own (copied into model_headers). */
static int request_headers(const pic_model *m, pic_auth_style auth, const char *const *extra, size_t nextra,
                           char *auth_line, size_t auth_cap, char *model_headers, size_t model_cap, const char **headers,
                           size_t *count, char *err, size_t errcap) {
    char key[KEY_CAP];
    size_t nheaders = 0;
    int 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, auth_cap,
                       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, model_cap, "%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;
    }
    *count = nheaders;
    return 0;
}

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 auth_line[KEY_CAP + 32], model_headers[sizeof m->headers];
    const char *headers[MAX_HEADERS];
    size_t nheaders = 0;
    int rc = -1;
    *retryable = 0;
    if (request_id_cap) {
        request_id[0] = '\0';
    }
    if (request_headers(m, auth, extra, nextra, auth_line, sizeof auth_line, model_headers, sizeof model_headers, headers,
                        &nheaders, err, errcap) != 0) {
        return -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 (s->no_retry || s->abort_retry) {
            break;
        }
        if (tryno < HTTP_TRIES) {
            long ms = backoff_ms(post == 0 ? &resp : NULL, tryno);
            pic_ev_retry_wait(s, tryno + 1, HTTP_TRIES, ms, err);
            pause_ms(s, ms);
            if (s->abort_retry) {
                break;
            }
        }
    }
    pic_cred_wipe(auth_line, sizeof auth_line);
    if (rc == 0) {
        *retryable = 0;
    }
    return rc;
}

/* A plain JSON reply's body, gathered whatever the status. */
typedef struct {
    pic_http_resp *resp;
    char *buf;
    size_t len, cap;
    int full;
} gather;

static int on_json(void *ctx, const char *bytes, size_t n) {
    gather *g = ctx;
    if (g->len + n + 1 > g->cap) {
        size_t cap = g->cap ? g->cap : 4096;
        char *grown;
        while (cap < g->len + n + 1) {
            cap *= 2;
        }
        if (cap > (16u << 20) || !(grown = realloc(g->buf, cap))) {
            g->full = 1;
            return -1;
        }
        g->buf = grown;
        g->cap = cap;
    }
    memcpy(g->buf + g->len, bytes, n);
    g->len += n;
    g->buf[g->len] = '\0';
    return 0;
}

int pic_json_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, char **out, char *err, size_t errcap) {
    char auth_line[KEY_CAP + 32], model_headers[sizeof m->headers];
    const char *headers[MAX_HEADERS];
    size_t nheaders = 0;
    int rc = -1;
    *out = NULL;
    if (request_headers(m, auth, extra, nextra, auth_line, sizeof auth_line, model_headers, sizeof model_headers, headers,
                        &nheaders, err, errcap) != 0) {
        return -1;
    }
    for (int tryno = 1; tryno <= HTTP_TRIES; tryno++) {
        pic_http_resp resp;
        gather g;
        int post, transient;
        memset(&g, 0, sizeof g);
        g.resp = &resp;
        pic_http_resp_init(&resp, on_json, &g);
        post = pic_http_post(net, url, headers, nheaders, body, strlen(body), &resp, idle_seconds(), DEADLINE_SECONDS,
                             err, errcap);
        if (post == 0 && resp.status == 200 && g.buf) {
            *out = g.buf;
            rc = 0;
            break;
        }
        transient = post != 0 ? !pic_net_tls_failed(net) && !g.full
                              : resp.status == 429 || resp.status == 529 || resp.status >= 500;
        if (post == 0) {
            error_text(s, resp.status, g.buf ? g.buf : "", err, errcap);
        }
        free(g.buf);
        if (!transient) {
            break;
        }
        if (tryno < HTTP_TRIES) {
            pause_ms(s, backoff_ms(post == 0 ? &resp : NULL, tryno));
        }
    }
    pic_cred_wipe(auth_line, sizeof auth_line);
    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;
}

long pic_cache_seconds(const pic_model *model) {
    pic_cache r = pic_cache_retention();
    if (r == PIC_CACHE_NONE) {
        return 0;
    }
    if (r == PIC_CACHE_SHORT || (model && !model->compat.supports_long_cache)) {
        return 300;
    }
    /* long: Anthropic's ttl (also Chat Completions with cache_control), or
     * OpenAI's prompt_cache_retention of 24h. */
    if (model && (model->api == PIC_API_RESPONSES || (model->api == PIC_API_CHAT && !model->compat.anthropic_cache_control))) {
        return 86400;
    }
    return model && model->api == PIC_API_GEMINI ? 300 : 3600;
}

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) {
    p->cache_seconds = pic_cache_seconds(model);
    p->count = NULL;
    (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;
}