/* 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 oc_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 oc_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 oc_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 oc_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 oc_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) {
oc_fail(c, "malformed chunk JSON");
}
(void)sqlite3_reset(st);
(void)sqlite3_clear_bindings(st);
if (!cached) {
sqlite3_finalize(st);
}
return c->failed ? -1 : 0;
}
/* Every field a chunk can carry, in one cached query. Invalid JSON yields a
* row whose first column is 0 rather than an error. */
static const char fields_sql[] =
"SELECT v, CASE WHEN v THEN json_extract(?1,'$.error') END,"
" CASE WHEN v AND json_type(?1,'$.usage')='object' THEN json_extract(?1,'$.usage') END,"
" CASE WHEN v AND json_type(?1,'$.choices[0].delta.reasoning_content')='text'"
" THEN json_extract(?1,'$.choices[0].delta.reasoning_content') END,"
" CASE WHEN v AND json_type(?1,'$.choices[0].delta.reasoning')='text' THEN json_extract(?1,'$.choices[0].delta.reasoning') END,"
" CASE WHEN v AND json_type(?1,'$.choices[0].delta.reasoning_text')='text'"
" THEN json_extract(?1,'$.choices[0].delta.reasoning_text') END,"
" CASE WHEN v AND json_type(?1,'$.choices[0].delta.content')='text' THEN json_extract(?1,'$.choices[0].delta.content') END,"
" CASE WHEN v AND json_type(?1,'$.choices[0].delta.tool_calls')='array'"
" THEN json_extract(?1,'$.choices[0].delta.tool_calls') END,"
" CASE WHEN v AND json_type(?1,'$.choices[0].delta.reasoning_details')='array'"
" THEN json_extract(?1,'$.choices[0].delta.reasoning_details') END,"
" CASE WHEN v THEN json_extract(?1,'$.choices[0].finish_reason') END"
" FROM (SELECT json_valid(?1) AND json_type(?1)='object' AS v)";
/* Copies a text column (or NULL) of the cached statement. */
static char *col(pic_chat *c, sqlite3_stmt *q, int i) {
char *s;
if (sqlite3_column_type(q, i) == SQLITE_NULL) {
return NULL;
}
s = dup_n((const char *)sqlite3_column_text(q, i), (size_t)sqlite3_column_bytes(q, i));
if (!s) {
oc_fail(c, "out of memory");
}
return s;
}
int pic_chat_init(pic_chat *c, sqlite3 *db) {
memset(c, 0, sizeof *c);
c->db = db;
if (sqlite3_prepare_v2(db, fields_sql, -1, &c->fields, NULL) != SQLITE_OK ||
sqlite3_prepare_v2(db, "SELECT value FROM json_each(?1) ORDER BY key", -1, &c->each, NULL) != SQLITE_OK ||
sqlite3_prepare_v2(db,
"SELECT json_extract(?1,'$.index'), json_extract(?1,'$.id'),"
" json_extract(?1,'$.function.name'), json_extract(?1,'$.function.arguments')",
-1, &c->call, NULL) != SQLITE_OK) {
return -1;
}
return 0;
}
void pic_chat_free(pic_chat *c) {
sqlite3_finalize(c->fields);
sqlite3_finalize(c->each);
sqlite3_finalize(c->call);
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;
sqlite3_bind_text(c->call, 1, call, (int)n, SQLITE_STATIC);
if (sqlite3_step(c->call) != SQLITE_ROW) {
(void)sqlite3_reset(c->call);
rc = oc_fail(c, "malformed tool call delta");
goto done;
}
index = col(c, c->call, 0);
id = col(c, c->call, 1);
name = col(c, c->call, 2);
args = col(c, c->call, 3);
(void)sqlite3_reset(c->call);
(void)sqlite3_clear_bindings(c->call);
if (c->failed) {
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 = oc_fail(c, "tool call index %ld out of order", ix);
goto done;
}
if (c->ncalls == PIC_CHAT_CALLS) {
rc = oc_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;
}
/* Runs fn on each element of a JSON array, in order. */
static int each(pic_chat *c, const char *array, int (*fn)(pic_chat *, const char *, size_t)) {
int rc = 0, step;
sqlite3_bind_text(c->each, 1, array, -1, SQLITE_STATIC);
while (rc == 0 && (step = sqlite3_step(c->each)) == SQLITE_ROW) {
const char *item = (const char *)sqlite3_column_text(c->each, 0);
rc = fn(c, item, (size_t)sqlite3_column_bytes(c->each, 0));
}
(void)sqlite3_reset(c->each);
(void)sqlite3_clear_bindings(c->each);
return rc;
}
static int detail(pic_chat *c, const char *item, size_t n) {
return (c->details.len ? add(c, &c->details, ",", 1) : 0) || add(c, &c->details, item, n);
}
static int chunk(pic_chat *c, const char *data, size_t len) {
static const char *const names[] = {"reasoning_content", "reasoning", "reasoning_text"};
sqlite3_stmt *q = c->fields;
char *error = NULL, *usage = NULL, *text = NULL, *calls = NULL, *details = NULL, *finish = NULL;
int rc = 0;
sqlite3_bind_text(q, 1, data, (int)len, SQLITE_STATIC);
if (sqlite3_step(q) != SQLITE_ROW) {
(void)sqlite3_reset(q);
return oc_fail(c, "malformed chunk JSON");
}
if (!sqlite3_column_int(q, 0)) {
(void)sqlite3_reset(q);
return oc_fail(c, "a chunk that is not a JSON object");
}
error = col(c, q, 1);
usage = col(c, q, 2);
/* Reasoning before content, as Pi handles them: the first non-empty field. */
for (int i = 0; i < 3 && rc == 0; i++) {
const char *r = (const char *)sqlite3_column_text(q, 3 + i);
if (r && *r) {
if (!c->reasoning_field[0]) {
(void)snprintf(c->reasoning_field, sizeof c->reasoning_field, "%s", names[i]);
}
rc = add(c, &c->reasoning, r, (size_t)sqlite3_column_bytes(q, 3 + i));
if (rc == 0 && c->on_delta) {
c->on_delta(c->delta_ctx, 1, r, (size_t)sqlite3_column_bytes(q, 3 + i));
}
break;
}
}
text = col(c, q, 6);
calls = col(c, q, 7);
details = col(c, q, 8);
finish = col(c, q, 9);
(void)sqlite3_reset(q);
(void)sqlite3_clear_bindings(q);
if (rc != 0 || c->failed) {
rc = -1;
goto done;
}
if (error) {
char *msg = NULL;
(void)oc_sql_text(c, NULL,
"SELECT CASE WHEN json_type(?1,'$.retryable')='false'"
" THEN coalesce(json_extract(?1,'$.type')||': ','')||coalesce(json_extract(?1,'$.message'),'error') END",
&msg, 1, error, strlen(error));
c->final_error = msg != NULL;
if (!msg) {
(void)oc_sql_text(c, NULL, "SELECT coalesce(json_extract(?1,'$.message'), ?1)", &msg, 1, error, strlen(error));
}
c->error = msg ? msg : dup_n("error", 5);
goto done; /* finish() reports it: the stream failed */
}
if (usage) {
free(c->usage);
c->usage = usage;
usage = NULL;
}
if (details && (rc = each(c, details, detail)) != 0) {
goto done;
}
if (text && c->on_delta) {
c->on_delta(c->delta_ctx, 0, text, strlen(text));
}
if (text && (rc = add(c, &c->text, text, strlen(text))) != 0) {
goto done;
}
if (calls && (rc = each(c, calls, tool_delta)) != 0) {
goto done;
}
if (finish) {
free(c->finish_reason);
c->finish_reason = finish;
finish = NULL;
}
done:
free(error);
free(usage);
free(text);
free(calls);
free(details);
free(finish);
return rc;
}
int pic_chat_event(void *ctx, const char *event, const char *data, size_t len) {
pic_chat *c = ctx;
(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;
}
return chunk(c, data, len);
}
int pic_chat_finish(pic_chat *c) {
if (c->failed) {
return -1;
}
if (c->error) {
return oc_fail(c, "%.200s", c->error);
}
if (!c->finish_reason) {
return oc_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 oc_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 oc_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)oc_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)oc_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)oc_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)oc_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;
}