Artifact 54f0eb7b6abb018a67eb4649ace624d07761a69bf8ca22d86fa28cd090c1577c:
- File
src/openai_responses.c
— part of check-in
[9dabe49948]
at
2026-11-21 19:00:33
on branch amalgam
— Amalgamation: pic as one pic.c beside the vendored sources, built by one cc line
make amalgamation writes pic-amalgamation-VERSION/ and its tarball; make test-amal builds it from the README's own line and runs crash, print and tools against that binary, and is part of make test-pic. About 60 file-local names that collided in one translation unit take their file's prefix; test/pic/amalgam.sh fails on a new collision. (user: dmestas, size: 10162) [annotate] [blame] [check-ins using] [more...]
/* OpenAI Responses stream decoder, following Pi's openai-responses adapter: * output items are kept whole (a reasoning item is replayed as streamed, * encrypted_content included); the terminal event's output list is * authoritative and fills in anything the per-item events lacked; status * completed is stop (toolUse with function calls), incomplete for * max_output_tokens is length, anything else fails the stream. */ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "openai_responses.h" static int ors_fail(pic_responses *r, const char *fmt, ...) { va_list ap; if (!r->failed) { va_start(ap, fmt); (void)vsnprintf(r->err, sizeof r->err, fmt, ap); va_end(ap); r->failed = 1; } return -1; } static char *ors_dup_n(const char *s, size_t n) { char *p = malloc(n + 1); if (p) { memcpy(p, s, n); p[n] = '\0'; } return p; } /* SELECT with text arguments; *out gets column 0 or NULL. */ static int ors_sql_text(pic_responses *r, const char *sql, char **out, int nargs, ...) { sqlite3_stmt *st = NULL; va_list ap; int rc; *out = NULL; if (sqlite3_prepare_v2(r->db, sql, -1, &st, NULL) != SQLITE_OK) { return ors_fail(r, "json: %s", sqlite3_errmsg(r->db)); } va_start(ap, nargs); for (int i = 1; i <= nargs; i++) { const char *s = va_arg(ap, const char *); size_t n = va_arg(ap, size_t); (void)sqlite3_bind_text(st, i, s, (int)n, SQLITE_STATIC); } va_end(ap); rc = sqlite3_step(st); if (rc == SQLITE_ROW && sqlite3_column_type(st, 0) != SQLITE_NULL) { *out = ors_dup_n((const char *)sqlite3_column_text(st, 0), (size_t)sqlite3_column_bytes(st, 0)); if (!*out) { rc = SQLITE_NOMEM; } } sqlite3_finalize(st); if (rc != SQLITE_ROW && rc != SQLITE_DONE) { return ors_fail(r, "malformed event JSON"); } return 0; } static int ors_get(pic_responses *r, const char *data, size_t len, const char *path, char **out) { return ors_sql_text(r, "SELECT json_extract(?1, ?2)", out, 2, data, len, path, strlen(path)); } static int keep(pic_responses *r, char **slot, char *value) { size_t n = value ? strlen(value) : 0; if (n > PIC_RESPONSES_CAP - r->total) { free(value); return ors_fail(r, "reply exceeds %u bytes", PIC_RESPONSES_CAP); } r->total += n; free(*slot); *slot = value; return 0; } int pic_responses_init(pic_responses *r, sqlite3 *db) { memset(r, 0, sizeof *r); r->db = db; return 0; } void pic_responses_free(pic_responses *r) { for (int i = 0; i < r->nitems; i++) { free(r->items[i]); } free(r->final_output); free(r->status); free(r->incomplete); free(r->usage); free(r->response_id); free(r->error); memset(r, 0, sizeof *r); } /* The response object of a terminal event: status, output, usage. */ static int terminal(pic_responses *r, const char *data, size_t len) { char *s = NULL; r->terminal = 1; if (ors_get(r, data, len, "$.response.status", &s) != 0 || keep(r, &r->status, s) != 0) { return -1; } if (ors_get(r, data, len, "$.response.incomplete_details.reason", &s) != 0 || keep(r, &r->incomplete, s) != 0) { return -1; } if (ors_sql_text(r, "SELECT CASE json_type(?1,'$.response.output') WHEN 'array' THEN json_extract(?1,'$.response.output') END", &s, 1, data, len) != 0 || keep(r, &r->final_output, s) != 0) { return -1; } if (ors_sql_text(r, "SELECT CASE json_type(?1,'$.response.usage') WHEN 'object' THEN json_extract(?1,'$.response.usage') END", &s, 1, data, len) != 0 || keep(r, &r->usage, s) != 0) { return -1; } if (ors_get(r, data, len, "$.response.error.message", &s) != 0) { return -1; } if (s) { return keep(r, &r->error, s); } return 0; } int pic_responses_event(void *ctx, const char *event, const char *data, size_t len) { pic_responses *r = ctx; char *type = NULL, *s = NULL; int rc = 0; (void)event; if (r->failed) { return -1; } if (r->terminal) { return 0; /* nothing after the terminal event matters */ } if (ors_sql_text(r, "SELECT CASE WHEN json_valid(?1) AND json_type(?1)='object' THEN json_extract(?1,'$.type') END", &type, 1, data, len) != 0) { return -1; } if (!type) { return ors_fail(r, "an event that is not a typed JSON object"); } if (strcmp(type, "response.created") == 0) { rc = ors_get(r, data, len, "$.response.id", &s) == 0 ? keep(r, &r->response_id, s) : -1; } else if (strcmp(type, "response.output_item.done") == 0) { char *ix = NULL; long i; if (ors_get(r, data, len, "$.output_index", &ix) != 0 || ors_sql_text(r, "SELECT CASE json_type(?1,'$.item') WHEN 'object' THEN json_extract(?1,'$.item') END", &s, 1, data, len) != 0) { free(ix); free(type); return -1; } i = ix ? strtol(ix, NULL, 10) : -1; free(ix); if (!s || i < 0 || i >= PIC_RESPONSES_ITEMS) { free(s); rc = ors_fail(r, "output item without an object or a usable index"); } else { while (r->nitems <= i) { r->items[r->nitems++] = NULL; } rc = keep(r, &r->items[i], s); } } else if (strcmp(type, "response.completed") == 0 || strcmp(type, "response.incomplete") == 0 || strcmp(type, "response.failed") == 0) { rc = terminal(r, data, len); } else if (strcmp(type, "error") == 0) { if (ors_sql_text(r, "SELECT coalesce(json_extract(?1,'$.message'), json_extract(?1,'$.error.message'), 'error')", &s, 1, data, len) == 0) { rc = keep(r, &r->error, s); r->terminal = 1; } else { rc = -1; } } /* Deltas and other events carry nothing the complete items lack. */ free(type); return rc; } int pic_responses_finish(pic_responses *r) { if (r->failed) { return -1; } if (r->error) { return ors_fail(r, "%.200s", r->error); } if (!r->terminal) { return ors_fail(r, "stream ended without response.completed"); } if (!r->status) { return ors_fail(r, "terminal event without a status"); } if (strcmp(r->status, "completed") != 0 && !(strcmp(r->status, "incomplete") == 0 && r->incomplete && strcmp(r->incomplete, "max_output_tokens") == 0)) { return ors_fail(r, "response %s%s%.60s", r->status, r->incomplete ? ": " : "", r->incomplete ? r->incomplete : ""); } return 0; } /* The output items: the terminal event's list when it has one (it is * authoritative), else the per-item events in order. */ char *pic_responses_native(pic_responses *r) { sqlite3_str *out; if (r->final_output) { return ors_dup_n(r->final_output, strlen(r->final_output)); } out = sqlite3_str_new(r->db); sqlite3_str_appendall(out, "["); for (int i = 0, first = 1; i < r->nitems; i++) { if (r->items[i]) { sqlite3_str_appendall(out, first ? "" : ","); sqlite3_str_appendall(out, r->items[i]); first = 0; } } sqlite3_str_appendall(out, "]"); { char *t = sqlite3_str_finish(out), *res = t ? ors_dup_n(t, strlen(t)) : NULL; sqlite3_free(t); return res; } } char *pic_responses_neutral(pic_responses *r) { char *native = pic_responses_native(r), *out = NULL; if (!native) { return NULL; } /* Pi's mapping: reasoning -> thinking (summary texts joined by a blank * line, else content texts; the whole item is the signature); message * -> text (output_text or refusal parts); function_call -> toolCall * with id "call_id|item_id" and its arguments parsed. */ (void)ors_sql_text( r, "SELECT coalesce(json_group_array(json(x)), '[]') FROM (SELECT CASE json_extract(o.value,'$.type')" " WHEN 'reasoning' THEN json_object('type','thinking','thinking',coalesce(" " (SELECT group_concat(json_extract(s.value,'$.text'), char(10,10)) FROM json_each(o.value,'$.summary') s)," " (SELECT group_concat(json_extract(c.value,'$.text'), char(10,10)) FROM json_each(o.value,'$.content') c), '')," " 'signature', o.value || '')" " WHEN 'message' THEN json_object('type','text','text',coalesce((SELECT group_concat(coalesce(" " json_extract(c.value,'$.text'), json_extract(c.value,'$.refusal')), '') FROM json_each(o.value,'$.content') c),''))" " WHEN 'function_call' THEN json_object('type','toolCall','id'," " coalesce(json_extract(o.value,'$.call_id'),'') || '|' || coalesce(json_extract(o.value,'$.id'),'')," " 'name',coalesce(json_extract(o.value,'$.name'),''),'arguments'," " CASE WHEN coalesce(json_extract(o.value,'$.arguments'),'') = '' THEN json('{}')" " WHEN json_valid(json_extract(o.value,'$.arguments')) AND json_type(json_extract(o.value,'$.arguments'))='object'" " THEN json(json_extract(o.value,'$.arguments'))" " ELSE json_object('pic_invalid_input', json_extract(o.value,'$.arguments')) END)" " END AS x FROM json_each(?1) o ORDER BY o.key) WHERE x IS NOT NULL", &out, 1, native, strlen(native)); free(native); return out; } const char *pic_responses_stop(pic_responses *r) { char *native, *n = NULL; int calls = 0; if (r->status && strcmp(r->status, "incomplete") == 0) { return "length"; } native = pic_responses_native(r); if (native) { (void)ors_sql_text(r, "SELECT count(*) FROM json_each(?1) WHERE json_extract(value,'$.type')='function_call'", &n, 1, native, strlen(native)); calls = n && strcmp(n, "0") != 0; free(n); free(native); } return calls ? "toolUse" : "stop"; }