Artifact d5ea461ed58cfadef13926f78447afcd4ed9bac04f429c5d99f3ef84ec9f516f:
- File
src/openai_chat.c
— part of check-in
[55cff08c2c]
at
2026-11-19 00:56:53
on branch stage-4
— Add the Chat Completions adapter for OpenAI, OpenRouter and compatibles
A chunk decoder following Pi: text, reasoning from reasoning_content, reasoning or reasoning_text kept under its field, OpenRouter reasoning_details verbatim, tool calls by index, usage, finish_reason, and in-stream errors. Requests follow Pi too: system or developer role, tools as functions, tool messages, stream_options, store and reasoning by dialect. The retry loop and header assembly move into a shared module both adapters use. Recorded streams, a fuzz target and fake server cases cover it, including a conversation moving between the two APIs in both directions. (user: dmestas, size: 14885) [annotate] [blame] [check-ins using]
/* Chat Completions stream decoder, following Pi's openai-completions * adapter: only choices[0] is read; reasoning comes from the first non-empty * of delta.reasoning_content, delta.reasoning, delta.reasoning_text (the * field is remembered so a replay sends it back under the same name), or * from OpenRouter's delta.reasoning_details, whose items are kept verbatim; * tool calls are assembled by their index; usage is taken from whichever * chunk carries it; finish_reason ends the message. */ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "openai_chat.h" static int fail(pic_chat *c, const char *fmt, ...) { va_list ap; if (!c->failed) { va_start(ap, fmt); (void)vsnprintf(c->err, sizeof c->err, fmt, ap); va_end(ap); c->failed = 1; } return -1; } static int add(pic_chat *c, pic_chat_buf *b, const char *s, size_t n) { if (n > PIC_CHAT_CAP - c->total) { return fail(c, "assistant message exceeds %u bytes", PIC_CHAT_CAP); } if (b->len + n + 1 > b->cap) { size_t cap = b->cap ? b->cap : 256; char *p; while (cap < b->len + n + 1) { cap *= 2; } if (!(p = realloc(b->buf, cap))) { return fail(c, "out of memory"); } b->buf = p; b->cap = cap; } memcpy(b->buf + b->len, s, n); b->len += n; b->buf[b->len] = '\0'; c->total += n; return 0; } static char *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. -1 on bad JSON. */ static int sql_text(pic_chat *c, sqlite3_stmt *cached, const char *sql, char **out, int nargs, ...) { sqlite3_stmt *st = cached; va_list ap; int rc; *out = NULL; if (!st && sqlite3_prepare_v2(c->db, sql, -1, &st, NULL) != SQLITE_OK) { return fail(c, "json: %s", sqlite3_errmsg(c->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 = dup_n((const char *)sqlite3_column_text(st, 0), (size_t)sqlite3_column_bytes(st, 0)); if (!*out) { rc = SQLITE_NOMEM; } } if (rc != SQLITE_ROW && rc != SQLITE_DONE) { fail(c, "malformed chunk JSON"); } (void)sqlite3_reset(st); (void)sqlite3_clear_bindings(st); if (!cached) { sqlite3_finalize(st); } return c->failed ? -1 : 0; } static int get(pic_chat *c, const char *data, size_t len, const char *path, char **out) { return sql_text(c, c->get, NULL, out, 2, data, len, path, strlen(path)); } int pic_chat_init(pic_chat *c, sqlite3 *db) { memset(c, 0, sizeof *c); c->db = db; return sqlite3_prepare_v2(db, "SELECT json_extract(?1, ?2)", -1, &c->get, NULL) == SQLITE_OK ? 0 : -1; } void pic_chat_free(pic_chat *c) { sqlite3_finalize(c->get); free(c->finish_reason); free(c->text.buf); free(c->reasoning.buf); free(c->details.buf); for (int i = 0; i < c->ncalls; i++) { free(c->calls[i].id); free(c->calls[i].name); free(c->calls[i].args.buf); } free(c->usage); free(c->error); memset(c, 0, sizeof *c); } /* One element of delta.tool_calls. */ static int tool_delta(pic_chat *c, const char *call, size_t n) { char *index = NULL, *id = NULL, *name = NULL, *args = NULL; pic_chat_call *slot = NULL; long ix = -1; int rc = 0; if (get(c, call, n, "$.index", &index) != 0 || get(c, call, n, "$.id", &id) != 0 || get(c, call, n, "$.function.name", &name) != 0 || get(c, call, n, "$.function.arguments", &args) != 0) { rc = -1; goto done; } ix = index ? strtol(index, NULL, 10) : -1; /* Keyed by index; a server that sends none is keyed by id (Pi's fallback). */ for (int i = 0; i < c->ncalls && !slot; i++) { if (ix >= 0 ? (long)i == ix : (id && c->calls[i].id && strcmp(c->calls[i].id, id) == 0)) { slot = &c->calls[i]; } } if (!slot) { if (ix >= 0 && ix != c->ncalls) { rc = fail(c, "tool call index %ld out of order", ix); goto done; } if (c->ncalls == PIC_CHAT_CALLS) { rc = fail(c, "more than %d tool calls", PIC_CHAT_CALLS); goto done; } slot = &c->calls[c->ncalls++]; } if (id && !slot->id) { slot->id = id; id = NULL; } if (name && !slot->name) { slot->name = name; name = NULL; } if (args) { rc = add(c, &slot->args, args, strlen(args)); } done: free(index); free(id); free(name); free(args); return rc; } static int chunk(pic_chat *c, const char *data, size_t len) { static const char *const fields[] = {"reasoning_content", "reasoning", "reasoning_text"}; char *s = NULL; int rc = 0; if (get(c, data, len, "$.error", &s) != 0) { return -1; } if (s) { char *msg = NULL; (void)sql_text(c, NULL, "SELECT coalesce(json_extract(?1,'$.message'), ?1)", &msg, 1, s, strlen(s)); free(s); c->error = msg ? msg : dup_n("error", 5); return 0; /* finish() reports it: the stream failed */ } if (get(c, data, len, "$.usage", &s) != 0) { return -1; } if (s && strcmp(s, "null") != 0 && s[0] == '{') { free(c->usage); c->usage = s; } else { free(s); } /* Reasoning before content, as Pi handles them. */ for (size_t i = 0; i < sizeof fields / sizeof fields[0]; i++) { char path[64]; (void)snprintf(path, sizeof path, "$.choices[0].delta.%s", fields[i]); if (sql_text(c, NULL, "SELECT CASE json_type(?1, ?2) WHEN 'text' THEN json_extract(?1, ?2) END", &s, 2, data, len, path, strlen(path)) != 0) { return -1; } if (s && *s) { if (!c->reasoning_field[0]) { (void)snprintf(c->reasoning_field, sizeof c->reasoning_field, "%s", fields[i]); } rc = add(c, &c->reasoning, s, strlen(s)); free(s); break; } free(s); } if (rc != 0) { return -1; } { sqlite3_stmt *q = NULL; if (sqlite3_prepare_v2(c->db, "SELECT value FROM json_each(?1, '$.choices[0].delta.reasoning_details') ORDER BY key", -1, &q, NULL) != SQLITE_OK) { return fail(c, "json: %s", sqlite3_errmsg(c->db)); } sqlite3_bind_text(q, 1, data, (int)len, SQLITE_STATIC); while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) { const char *item = (const char *)sqlite3_column_text(q, 0); rc = (c->details.len ? add(c, &c->details, ",", 1) : 0) || add(c, &c->details, item, strlen(item)); } sqlite3_finalize(q); if (rc != 0) { return -1; } } if (sql_text(c, NULL, "SELECT CASE json_type(?1,'$.choices[0].delta.content') WHEN 'text'" " THEN json_extract(?1,'$.choices[0].delta.content') END", &s, 1, data, len) != 0) { return -1; } if (s) { rc = add(c, &c->text, s, strlen(s)); free(s); if (rc != 0) { return -1; } } { sqlite3_stmt *q = NULL; if (sqlite3_prepare_v2(c->db, "SELECT value FROM json_each(?1, '$.choices[0].delta.tool_calls') ORDER BY key", -1, &q, NULL) != SQLITE_OK) { return fail(c, "json: %s", sqlite3_errmsg(c->db)); } sqlite3_bind_text(q, 1, data, (int)len, SQLITE_STATIC); while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) { const char *call = (const char *)sqlite3_column_text(q, 0); rc = tool_delta(c, call, strlen(call)); } sqlite3_finalize(q); if (rc != 0) { return -1; } } if (get(c, data, len, "$.choices[0].finish_reason", &s) != 0) { return -1; } if (s) { free(c->finish_reason); c->finish_reason = s; } return 0; } int pic_chat_event(void *ctx, const char *event, const char *data, size_t len) { pic_chat *c = ctx; char *valid = NULL; (void)event; if (c->failed) { return -1; } if (c->done) { return 0; /* nothing after [DONE] matters */ } if (len == 6 && memcmp(data, "[DONE]", 6) == 0) { c->done = 1; return 0; } if (sql_text(c, NULL, "SELECT json_valid(?1) AND json_type(?1)='object'", &valid, 1, data, len) != 0) { return -1; } if (!valid || strcmp(valid, "1") != 0) { free(valid); return fail(c, "a chunk that is not a JSON object"); } free(valid); return chunk(c, data, len); } int pic_chat_finish(pic_chat *c) { if (c->failed) { return -1; } if (c->error) { return fail(c, "%.200s", c->error); } if (!c->finish_reason) { return fail(c, "stream ended without finish_reason"); } { const char *f = c->finish_reason; if (strcmp(f, "stop") != 0 && strcmp(f, "end") != 0 && strcmp(f, "length") != 0 && strcmp(f, "tool_calls") != 0 && strcmp(f, "function_call") != 0 && strcmp(f, "content_filter") != 0) { return fail(c, "provider finish_reason: %.60s", f); } } for (int i = 0; i < c->ncalls; i++) { if (!c->calls[i].id || !c->calls[i].name) { return fail(c, "tool call %d has no id or name", i); } } return 0; } const char *pic_chat_stop(const pic_chat *c) { const char *f = c->finish_reason ? c->finish_reason : "stop"; if (strcmp(f, "length") == 0) { return "length"; } if (strcmp(f, "tool_calls") == 0 || strcmp(f, "function_call") == 0) { return "toolUse"; } if (strcmp(f, "content_filter") == 0) { return "refusal"; } return c->ncalls > 0 ? "toolUse" : "stop"; } /* The tool calls as a JSON array, in either form. */ static char *calls_json(pic_chat *c, int neutral) { sqlite3_str *out = sqlite3_str_new(c->db); for (int i = 0; i < c->ncalls; i++) { const char *args = c->calls[i].args.buf ? c->calls[i].args.buf : ""; char *item = NULL; if (neutral) { /* Arguments that are not a JSON object are kept as a string under a * marker key: the tool rejects them, the history stays valid. */ (void)sql_text(c, NULL, "SELECT json_object('type','toolCall','id',?1,'name',?2,'arguments'," " CASE WHEN ?3 = '' THEN json('{}') WHEN json_valid(?3) AND json_type(?3)='object' THEN json(?3)" " ELSE json_object('pic_invalid_input', ?3) END)", &item, 3, c->calls[i].id, strlen(c->calls[i].id), c->calls[i].name, strlen(c->calls[i].name), args, strlen(args)); } else { (void)sql_text(c, NULL, "SELECT json_object('id',?1,'type','function','function',json_object('name',?2,'arguments',?3))", &item, 3, c->calls[i].id, strlen(c->calls[i].id), c->calls[i].name, strlen(c->calls[i].name), args, strlen(args)); } sqlite3_str_appendall(out, i ? "," : ""); sqlite3_str_appendall(out, item ? item : "null"); free(item); } { char *joined = sqlite3_str_finish(out), *res; size_t n = joined ? strlen(joined) : 0; res = malloc(n + 3); if (res) { res[0] = '['; if (n) { memcpy(res + 1, joined, n); } res[n + 1] = ']'; res[n + 2] = '\0'; } sqlite3_free(joined); return res; } } char *pic_chat_native(pic_chat *c) { char *calls = calls_json(c, 0), *out = NULL, *details = NULL; const char *text = c->text.buf ? c->text.buf : "", *reasoning = c->reasoning.buf ? c->reasoning.buf : ""; if (!calls) { return NULL; } if (c->details.len) { details = malloc(c->details.len + 3); if (details) { (void)snprintf(details, c->details.len + 3, "[%s]", c->details.buf); } } (void)sql_text(c, NULL, "SELECT json_patch(json_object('role','assistant','content',CASE WHEN ?1 = '' THEN NULL ELSE ?1 END)," " json_object('tool_calls', CASE WHEN ?2 = '[]' THEN NULL ELSE json(?2) END," " ?3, CASE WHEN ?3 = '' OR ?4 = '' THEN NULL ELSE ?4 END," " 'reasoning_details', CASE WHEN ?5 = '' THEN NULL ELSE json(?5) END))", &out, 5, text, strlen(text), calls, strlen(calls), c->reasoning_field[0] ? c->reasoning_field : "x", strlen(c->reasoning_field[0] ? c->reasoning_field : "x"), reasoning, strlen(reasoning), details ? details : "", details ? strlen(details) : (size_t)0); free(calls); free(details); return out; } char *pic_chat_neutral(pic_chat *c) { char *calls = calls_json(c, 1), *out = NULL, *signature = NULL; const char *text = c->text.buf ? c->text.buf : "", *reasoning = c->reasoning.buf ? c->reasoning.buf : ""; if (!calls) { return NULL; } /* Pi's thinkingSignature for this API: the reasoning_details JSON when * there are details, else the field the reasoning came in. */ if (c->details.len) { signature = malloc(c->details.len + 3); if (signature) { (void)snprintf(signature, c->details.len + 3, "[%s]", c->details.buf); } } else { signature = dup_n(c->reasoning_field, strlen(c->reasoning_field)); } (void)sql_text(c, NULL, "SELECT json_group_array(json(x)) FROM (" " SELECT 1 AS o, json_object('type','thinking','thinking',?1,'signature',?2) AS x" " WHERE ?1 != '' OR ?3 = '1'" " UNION ALL SELECT 2, json_object('type','text','text',?4) WHERE ?4 != ''" " UNION ALL SELECT 3 + key, value FROM json_each(?5) ORDER BY o)", &out, 5, reasoning, strlen(reasoning), signature ? signature : "", signature ? strlen(signature) : (size_t)0, c->details.len ? "1" : "0", (size_t)1, text, strlen(text), calls, strlen(calls)); free(calls); free(signature); return out; }