/* Chat Completions stream decoder (OpenAI, OpenRouter and compatible * servers): SSE "data:" chunks to "[DONE]" in, one assistant message out, in * the native form Chat Completions takes back and in Pi's neutral form. * Parsing follows Pi's openai-completions adapter; JSON is read with SQLite's * JSON functions on a caller-supplied connection. */ #ifndef PIC_OPENAI_CHAT_H #define PIC_OPENAI_CHAT_H #include #include "sqlite3.h" #define PIC_CHAT_CAP (16u << 20) /* bound on one assistant message */ #define PIC_CHAT_CALLS 64 /* tool calls in one message */ typedef struct { char *buf; size_t len, cap; } pic_chat_buf; typedef struct { char *id, *name; pic_chat_buf args; } pic_chat_call; typedef struct { sqlite3 *db; sqlite3_stmt *fields; /* every field of a chunk, in one query */ sqlite3_stmt *each; /* the elements of a JSON array */ sqlite3_stmt *call; /* every field of one tool-call delta */ int done; /* saw "[DONE]" */ char *finish_reason; /* the provider's, verbatim */ pic_chat_buf text, reasoning; char reasoning_field[24]; /* reasoning_content, reasoning or reasoning_text */ pic_chat_buf details; /* OpenRouter reasoning_details items, comma-joined JSON */ pic_chat_call calls[PIC_CHAT_CALLS]; int ncalls; char *usage; /* the usage object, verbatim */ char *error; /* an in-stream error object's message */ int final_error; /* that error says "retryable": false: "type: message" is final */ size_t total; /* Optional: each text or reasoning delta as it arrives (set after init). */ void (*on_delta)(void *ctx, int thinking, const char *text, size_t len); void *delta_ctx; int failed; char err[256]; } pic_chat; int pic_chat_init(pic_chat *c, sqlite3 *db); void pic_chat_free(pic_chat *c); /* Fits pic_sse_event_fn with ctx = the decoder. 0, or -1 with c->err set. */ int pic_chat_event(void *ctx, const char *event, const char *data, size_t len); /* End of stream. 0 when a complete message arrived (a finish_reason was * seen and no error), else -1 with c->err saying why; c->final_error is set * when the error said "retryable": false. */ int pic_chat_finish(pic_chat *c); /* After a successful finish (malloc'd, or NULL on failure): * the assistant message as Chat Completions takes it back, verbatim; */ char *pic_chat_native(pic_chat *c); /* Pi's neutral content array; */ char *pic_chat_neutral(pic_chat *c); /* Pi's stop reason: stop, length, toolUse, refusal. */ const char *pic_chat_stop(const pic_chat *c); /* The Chat Completions adapter (provider_chat.c), for the composition root. */ struct pic_provider_adapter; extern const struct pic_provider_adapter pic_chat_adapter; #endif