Artifact 5cef657208ce9edb9738dba17027fda5db385841441273122aecc3626af4bebb:
- File
src/provider_anthropic.c
— part of check-in
[9983dd9955]
at
2026-11-19 11:05:56
on branch events
— Stream live events: Pi's JSON-mode events, or the reply as it arrives
--json writes one event per line as the run goes, with Pi's names and shapes: agent, turn and message start and end, text and thinking deltas from every adapter, tool execution start and end, compaction start and end, and auto_retry_start. A reply cut off mid-stream ends in message_end with stopReason error before it is requested again, so a client drops the partial text. pic ask streams the reply text when stdout is a terminal (--stream forces it) and prints it only once; tool calls stay on stderr. Events are not journaled: the journal remains the record. (user: dmestas, size: 12739) [annotate] [blame] [check-ins using] [more...]
/* 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; 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',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',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_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); } static char *build_body(pic_store *s, const state *st, int64_t submission, const char *messages) { 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_object('model',?1,'max_tokens',?2,'stream',json('true'),'system',?3," "'tools',json(?4),'messages',json(?5))", -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, st->model.max_tokens < MAX_TOKENS ? st->model.max_tokens : 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); 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, 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; }