Skip to content
pi-c Documentation
Login

Documentation

/* 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