Artifact cddec3f0cfa4d7206a7ab84cd380ab4869c9ac2b47e4e865d25749f9f4b69c62:
- File
src/openai_chat.h
— 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: 2174) [annotate] [blame] [check-ins using]
/* 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 <stddef.h> #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 *get; /* SELECT json_extract(?1, ?2) */ 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 */ size_t total; 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. */ 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); #endif