Artifact 14eb745b4ce1a2358c619054367a38e5a6c1da3058a344db5b00f9b1699b12fc:
- File
src/provider_anthropic.c
— part of check-in
[c55dfbb163]
at
2026-11-19 23:39:49
on branch images
— Images, as Pi's
User messages, steering and follow-ups, and tool results can carry images. Journal version 9 keeps their bytes in SQLite (pic_image, deduplicated by SHA3-256, deflated only when smaller) linked by pic_attachment, written in the same transaction as the entry; pic check covers them. Each adapter sends its native shape (Anthropic base64 blocks, Chat image_url data URLs, Responses input_image); a model whose catalog input lacks images gets Pi's placeholders. pic ask --image PATH, the RPC images field and the read tool on image files add them; the Pi and HTML exports include them. (user: dmestas, size: 15480) [annotate] [blame] [check-ins using]
/* Messages API adapter: the request built from the journal, streamed through * the shared POST (provider_http.c) and the event decoder (anthropic.c). */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "anthropic.h" #include "provider_http.h" #define API_VERSION "2026-10-21" #define MAX_TOKENS 64000 typedef struct { pic_model model; /* provider, id, key and headers from the registry */ char *url, *workspace; pic_net *net; } state; /* The messages array: the user's text (and its images); each assistant turn verbatim if this * provider, API and model produced it, else rebuilt from its neutral form * (thinking dropped, tool-call ids normalised); each run of tool results as * one user message, with ids normalised exactly as their calls were. */ static char *build_messages(pic_store *s, const state *st, int64_t submission, char *err, size_t errcap) { sqlite3_stmt *q = NULL; sqlite3_str *out = sqlite3_str_new(s->db); int in_results = 0, first = 1, step; if (sqlite3_prepare_v2( s->db, PIC_CONTEXT_CTE "SELECT e.kind, CASE e.kind" " WHEN 'user' THEN json_object('role','user','content'," " coalesce(json(pic_content(e.seq,e.body,'anthropic-user',?5)),e.body))" " WHEN 'compaction' THEN json_object('role','user','content',json_array(json_object('type','text','text'," PIC_SUMMARY_SQL("e.body") ")))" " WHEN 'instructions' THEN json_object('type','text','text'," " '<project_instructions_update>' || char(10) || e.body || char(10) || '</project_instructions_update>')" " WHEN 'tool_result' THEN json_object('type','tool_result','tool_use_id'," " CASE WHEN a.seq > kk.cseq AND a.provider IS ?2 AND a.api IS ?3 AND a.model IS ?4 THEN f.call_id" " ELSE pic_norm_id(f.call_id,'anthropic-messages',?2) END," " 'content',coalesce(json(pic_content(e.seq,e.body,'anthropic-tool',?5)),e.body)," " 'is_error',json(iif(f.is_error,'true','false')))" " ELSE CASE WHEN v.fresh AND e.provider IS ?2 AND e.api IS ?3 AND e.model IS ?4" " THEN json_object('role','assistant','content',json(e.native))" " ELSE json_object('role','assistant','content',json((SELECT coalesce(json_group_array(json(y)),'[]') FROM" " (SELECT CASE json_extract(value,'$.type')" " WHEN 'text' THEN json_object('type','text','text',json_extract(value,'$.text'))" " WHEN 'toolCall' THEN json_object('type','tool_use','id'," " pic_norm_id(json_extract(value,'$.id'),'anthropic-messages',?2)," " 'name',json_extract(value,'$.name'),'input',json(json_extract(value,'$.arguments')))" " END AS y FROM json_each(e.body) ORDER BY key) WHERE y IS NOT NULL))) END END" " FROM pic_entry e JOIN v ON v.seq = e.seq CROSS JOIN kk LEFT JOIN pic_effect f ON f.id=e.effect_id" " LEFT JOIN pic_entry a ON a.seq=f.entry_seq ORDER BY e.kind != 'compaction', e.seq", -1, &q, NULL) != SQLITE_OK) { (void)snprintf(err, errcap, "sql: %s", sqlite3_errmsg(s->db)); sqlite3_free(sqlite3_str_finish(out)); return NULL; } sqlite3_bind_int64(q, 1, submission); sqlite3_bind_text(q, 2, st->model.provider, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, pic_api_name(st->model.api), -1, SQLITE_STATIC); sqlite3_bind_text(q, 4, st->model.id, -1, SQLITE_STATIC); sqlite3_bind_int(q, 5, st->model.image_input); sqlite3_str_appendall(out, "["); while ((step = sqlite3_step(q)) == SQLITE_ROW) { /* Tool results and instruction updates are blocks of one user message. */ const char *kind = (const char *)sqlite3_column_text(q, 0); int result = strcmp(kind, "tool_result") == 0 || strcmp(kind, "instructions") == 0; const char *item = (const char *)sqlite3_column_text(q, 1); /* A foreign turn with nothing this API can take (only thinking) is * left out; the API refuses an empty assistant message. */ if (item && strcmp(item, "{\"role\":\"assistant\",\"content\":[]}") == 0) { continue; } if (in_results && !result) { sqlite3_str_appendall(out, "]}"); in_results = 0; } if (result && in_results) { sqlite3_str_appendall(out, ","); } else { sqlite3_str_appendall(out, first ? "" : ","); if (result) { sqlite3_str_appendall(out, "{\"role\":\"user\",\"content\":["); in_results = 1; } } sqlite3_str_appendall(out, item ? item : "null"); first = 0; } sqlite3_finalize(q); if (in_results) { sqlite3_str_appendall(out, "]}"); } sqlite3_str_appendall(out, "]"); if (step != SQLITE_DONE || sqlite3_str_errcode(out) != SQLITE_OK) { (void)snprintf(err, errcap, "could not build the request"); sqlite3_free(sqlite3_str_finish(out)); return NULL; } return sqlite3_str_finish(out); } /* Pi's thinking budgets (simple-options.ts); xhigh and max take high's. */ static long thinking_budget(const char *level) { return strcmp(level, "minimal") == 0 ? 1024 : strcmp(level, "low") == 0 ? 2048 : strcmp(level, "medium") == 0 ? 8192 : 16384; } /* Pi's mapThinkingLevelToEffort for adaptive-thinking models. */ static const char *adaptive_effort(const pic_model *m, const char *level) { const char *mapped = NULL; if (pic_model_thinking_map(m, level, &mapped) == 2) { return mapped; } return strcmp(level, "minimal") == 0 || strcmp(level, "low") == 0 ? "low" : strcmp(level, "medium") == 0 ? "medium" : "high"; } /* The thinking and output_config members of a request at LEVEL, as JSON * (empty when none) and the max_tokens to send, as Pi's streamSimple does: * off sends thinking disabled for a reasoning model that may be off, adaptive * models an effort, others a token budget inside max_tokens. */ static long thinking_request(const pic_model *m, const char *level, char *thinking, size_t tcap, char *config, size_t ccap) { long max_tokens = m->max_tokens < MAX_TOKENS ? m->max_tokens : MAX_TOKENS; thinking[0] = config[0] = '\0'; if (!m->reasoning) { return max_tokens; } if (strcmp(level, "off") == 0) { if (pic_model_thinking_map(m, "off", NULL) != 1) { (void)snprintf(thinking, tcap, "{\"type\":\"disabled\"}"); } } else if (m->compat.force_adaptive_thinking) { (void)snprintf(thinking, tcap, "{\"type\":\"adaptive\",\"display\":\"summarized\"}"); (void)snprintf(config, ccap, "{\"effort\":\"%s\"}", adaptive_effort(m, level)); } else { long budget = thinking_budget(level); max_tokens = max_tokens + budget < m->max_tokens ? max_tokens + budget : m->max_tokens; if (budget > max_tokens - 1024) { /* leave 1024 tokens for the answer */ budget = max_tokens > 1024 ? max_tokens - 1024 : 0; } (void)snprintf(thinking, tcap, "{\"type\":\"enabled\",\"budget_tokens\":%ld,\"display\":\"summarized\"}", budget ? budget : 1024); } return max_tokens; } static char *build_body(pic_store *s, const state *st, const char *level, int64_t submission, const char *messages) { char thinking[128], config[64]; long max_tokens = thinking_request(&st->model, level, thinking, sizeof thinking, config, sizeof config); sqlite3_stmt *q = NULL; char *body = NULL, *system_prompt = pic_session_text(s, submission, "system_prompt"), *tools = pic_session_text(s, submission, "tools"); if (!system_prompt || !tools) { free(system_prompt); free(tools); return NULL; } if (sqlite3_prepare_v2(s->db, "SELECT json_patch(json_object('model',?1,'max_tokens',?2,'stream',json('true'),'system',?3," "'tools',json(?4),'messages',json(?5))," " json_object('thinking',json(nullif(?6,'')),'output_config',json(nullif(?7,''))))", -1, &q, NULL) != SQLITE_OK) { free(system_prompt); free(tools); return NULL; } sqlite3_bind_text(q, 1, st->model.id, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 2, max_tokens); sqlite3_bind_text(q, 3, system_prompt, -1, SQLITE_STATIC); sqlite3_bind_text(q, 4, tools, -1, SQLITE_STATIC); sqlite3_bind_text(q, 5, messages, -1, SQLITE_STATIC); sqlite3_bind_text(q, 6, thinking, -1, SQLITE_STATIC); sqlite3_bind_text(q, 7, config, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) { body = pic_strdup((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); free(system_prompt); free(tools); return body; } /* Pi's stop reasons from the Messages API's. */ static char *stop_reason(const char *s) { if (!s) { return NULL; } return pic_strdup(strcmp(s, "end_turn") == 0 || strcmp(s, "stop_sequence") == 0 ? "stop" : strcmp(s, "max_tokens") == 0 ? "length" : strcmp(s, "tool_use") == 0 ? "toolUse" : strcmp(s, "pause_turn") == 0 ? "pause" : s); } /* The event decoder, wrapped for pic_stream_post. */ typedef struct { sqlite3 *db; pic_anthropic dec; pic_store *stream; /* replies only: deltas go to its events */ } decoding; static int dec_begin(void *ctx) { decoding *d = ctx; if (pic_anthropic_init(&d->dec, d->db) != 0) { return -1; } if (d->stream) { d->dec.on_delta = pic_ev_delta; d->dec.delta_ctx = d->stream; } return 0; } static int dec_finish(void *ctx, char *why, size_t cap) { decoding *d = ctx; if (pic_anthropic_finish(&d->dec) == 0 && !d->dec.msg.error) { return 0; } (void)snprintf(why, cap, "%s", d->dec.msg.error ? d->dec.msg.error : d->dec.err); return -1; } static int dec_event(void *ctx, const char *event, const char *data, size_t len) { return pic_anthropic_event(&((decoding *)ctx)->dec, event, data, len); } static void dec_end(void *ctx) { pic_anthropic_free(&((decoding *)ctx)->dec); } static int anthropic_reply(pic_provider *p, pic_store *s, int64_t submission, int64_t turn, pic_reply *out, int *retryable, char *err, size_t errcap) { state *st = p->state; static const char *const extra[] = {"anthropic-version: " API_VERSION, "Accept: text/event-stream"}; decoding d; pic_stream_decoder dec = {dec_begin, dec_event, dec_finish, dec_end, &d}; char *messages, *body, request_id[128]; int rc; (void)turn; *retryable = 0; memset(out, 0, sizeof *out); memset(&d, 0, sizeof d); d.db = s->db; d.stream = s; messages = build_messages(s, st, submission, err, errcap); body = messages ? build_body(s, st, p->thinking, submission, messages) : NULL; sqlite3_free(messages); if (!body) { if (!err[0]) { (void)snprintf(err, errcap, "could not build the request body"); } return -1; } rc = pic_stream_post(st->net, s, &st->model, st->url, PIC_AUTH_X_API_KEY, extra, 2, body, &dec, request_id, sizeof request_id, retryable, err, errcap); free(body); if (rc != 0) { return -1; } out->native = d.dec.msg.content; d.dec.msg.content = NULL; out->neutral = out->native ? pic_neutral_from_anthropic(s->db, out->native) : NULL; out->stop_reason = stop_reason(d.dec.msg.stop_reason); out->usage = d.dec.msg.usage ? pic_strdup(d.dec.msg.usage) : NULL; out->request_id = request_id[0] ? pic_strdup(request_id) : NULL; out->provider = pic_strdup(st->model.provider); out->api = pic_strdup(pic_api_name(st->model.api)); out->model = pic_strdup(st->model.id); dec_end(&d); if (!out->native || !out->neutral || !out->provider || !out->api || !out->model) { pic_reply_free(out); (void)snprintf(err, errcap, "out of memory"); return -1; } return 0; } /* A plain request for compaction: SYSTEM and one USER message, no tools. */ static int anthropic_summarize(pic_provider *p, pic_store *s, const char *system, const char *user, char **text, char **usage, int *retryable, char *err, size_t errcap) { state *st = p->state; static const char *const extra[] = {"anthropic-version: " API_VERSION, "Accept: text/event-stream"}; decoding d; pic_stream_decoder dec = {dec_begin, dec_event, dec_finish, dec_end, &d}; char *body, *neutral; int rc; *text = *usage = NULL; memset(&d, 0, sizeof d); d.db = s->db; char max_tokens[24]; (void)snprintf(max_tokens, sizeof max_tokens, "%ld", st->model.max_tokens > 0 && st->model.max_tokens < MAX_TOKENS ? st->model.max_tokens : (long)MAX_TOKENS); body = pic_json_body(s->db, "SELECT json_object('model',?1,'max_tokens',CAST(?4 AS INTEGER),'stream',json('true'),'system',?2,'messages',json_array(json_object('role','user','content',?3)))", 4, st->model.id, system, user, max_tokens); if (!body) { (void)snprintf(err, errcap, "could not build the summary request"); return -1; } rc = pic_stream_post(st->net, s, &st->model, st->url, PIC_AUTH_X_API_KEY, extra, 2, body, &dec, NULL, 0, retryable, err, errcap); free(body); if (rc != 0) { return -1; } /* A summary cut off at the token cap is incomplete: never a checkpoint. */ if (d.dec.msg.stop_reason && strcmp(d.dec.msg.stop_reason, "max_tokens") == 0) { dec_end(&d); (void)snprintf(err, errcap, "the summary hit the token cap and is incomplete"); return -1; } neutral = pic_neutral_from_anthropic(s->db, d.dec.msg.content); *text = neutral ? pic_neutral_text(s->db, neutral) : NULL; *usage = d.dec.msg.usage ? pic_strdup(d.dec.msg.usage) : NULL; free(neutral); dec_end(&d); if (!*text) { (void)snprintf(err, errcap, "the summary reply had no text"); return -1; } return 0; } static void anthropic_free(pic_provider *p) { state *st = p->state; if (st) { pic_net_free(st->net); free(st->url); free(st->workspace); free(st); } p->state = NULL; } int pic_provider_anthropic_new(pic_provider *p, const pic_model *m, const char *url, const char *workspace, char *err, size_t errcap) { char endpoint[512]; state *st = calloc(1, sizeof *st); p->reply = anthropic_reply; p->summarize = anthropic_summarize; p->context_window = m->context_window; p->free = anthropic_free; p->state = st; if (!st) { (void)snprintf(err, errcap, "out of memory"); return -1; } st->model = *m; pic_model_url(m, endpoint, sizeof endpoint); if (!(st->url = pic_strdup(url ? url : endpoint)) || !(st->workspace = pic_strdup(workspace))) { (void)snprintf(err, errcap, "out of memory"); return -1; } st->net = pic_net_new(err, errcap); return st->net ? 0 : -1; }