Artifact 7196e07f76b421641ed995e2e8862bf63471260d13c3b64149fec29d6a35e663:
- File
src/provider_chat.c
— part of check-in
[9983dd9955]
at
2026-11-19 11:05:56
on branch events
— Stream live events: Pi's JSON-mode events, or the reply as it arrives
--json writes one event per line as the run goes, with Pi's names and shapes: agent, turn and message start and end, text and thinking deltas from every adapter, tool execution start and end, compaction start and end, and auto_retry_start. A reply cut off mid-stream ends in message_end with stopReason error before it is requested again, so a client drops the partial text. pic ask streams the reply text when stdout is a terminal (--stream forces it) and prints it only once; tool calls stay on stderr. Events are not journaled: the journal remains the record. (user: dmestas, size: 12901) [annotate] [blame] [check-ins using] [more...]
/* Chat Completions adapter (OpenAI, OpenRouter, OpenAI-compatible servers): * the request built from the journal as Pi's openai-completions adapter * builds it, streamed through the shared POST and the chunk decoder. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "openai_chat.h" #include "provider_http.h" #define REASONING_EFFORT "medium" /* Pi's default thinking level */ typedef struct { pic_model model; char *url, *workspace; pic_net *net; } state; /* One element per message: the system prompt, the user's text, each * assistant turn (verbatim to its own model, else rebuilt from the neutral * form: text joined, tool calls with normalised ids and arguments as a JSON * string, no reasoning), and each tool result as a "tool" message. */ static char *build_messages(pic_store *s, const state *st, int64_t submission, const char *system_prompt, char *err, size_t errcap) { sqlite3_stmt *q = NULL; sqlite3_str *out = sqlite3_str_new(s->db); const pic_compat *c = &st->model.compat; int step, first = 1; if (sqlite3_prepare_v2( s->db, PIC_CONTEXT_CTE "SELECT CASE e.kind" " WHEN 'user' THEN json_object('role','user','content',e.body)" " WHEN 'compaction' THEN json_object('role','user','content'," PIC_SUMMARY_SQL("e.body") ")" " WHEN 'instructions' THEN json_object('role','user','content'," " '<project_instructions_update>' || char(10) || e.body || char(10) || '</project_instructions_update>')" " WHEN 'tool_result' THEN json_object('role','tool','tool_call_id'," " CASE WHEN a.seq > kk.cseq AND a.provider IS ?2 AND a.api IS ?3 AND a.model IS ?4 THEN f.call_id" " ELSE pic_norm_id(f.call_id,'openai-completions',?2) END,'content',e.body)" " ELSE CASE WHEN v.fresh AND e.provider IS ?2 AND e.api IS ?3 AND e.model IS ?4 THEN json(e.native)" " ELSE (SELECT CASE WHEN t IS NULL AND n = 0 THEN NULL ELSE json_patch(" " json_object('role','assistant','content',t)," " json_object('tool_calls',CASE WHEN n = 0 THEN NULL ELSE json(calls) END," " 'reasoning_content',CASE WHEN ?5 THEN '' END)) END" " FROM (SELECT (SELECT group_concat(json_extract(value,'$.text'),'') FROM json_each(e.body)" " WHERE json_extract(value,'$.type')='text') AS t," " (SELECT count(*) FROM json_each(e.body) WHERE json_extract(value,'$.type')='toolCall') AS n," " (SELECT json_group_array(json_object('id',pic_norm_id(json_extract(value,'$.id')," " 'openai-completions',?2),'type','function','function',json_object('name'," " json_extract(value,'$.name'),'arguments',json_extract(value,'$.arguments') || '')))" " FROM json_each(e.body) WHERE json_extract(value,'$.type')='toolCall') AS calls)) END END" " FROM pic_entry e JOIN v ON v.seq = e.seq CROSS JOIN kk LEFT JOIN pic_effect f ON f.id=e.effect_id" " LEFT JOIN pic_entry a ON a.seq=f.entry_seq ORDER BY e.kind != 'compaction', e.seq", -1, &q, NULL) != SQLITE_OK) { (void)snprintf(err, errcap, "sql: %s", sqlite3_errmsg(s->db)); sqlite3_free(sqlite3_str_finish(out)); return NULL; } sqlite3_bind_int64(q, 1, submission); sqlite3_bind_text(q, 2, st->model.provider, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, pic_api_name(st->model.api), -1, SQLITE_STATIC); sqlite3_bind_text(q, 4, st->model.id, -1, SQLITE_STATIC); sqlite3_bind_int(q, 5, c->requires_reasoning_content); { /* The system prompt: developer role for reasoning models where the * server takes it, as Pi does. */ sqlite3_stmt *sp = NULL; if (sqlite3_prepare_v2(s->db, "SELECT json_object('role',?1,'content',?2)", -1, &sp, NULL) == SQLITE_OK) { sqlite3_bind_text(sp, 1, st->model.reasoning && c->supports_developer_role ? "developer" : "system", -1, SQLITE_STATIC); sqlite3_bind_text(sp, 2, system_prompt, -1, SQLITE_STATIC); if (sqlite3_step(sp) == SQLITE_ROW) { sqlite3_str_appendall(out, "["); sqlite3_str_appendall(out, (const char *)sqlite3_column_text(sp, 0)); first = 0; } sqlite3_finalize(sp); } } if (first) { sqlite3_str_appendall(out, "["); } while ((step = sqlite3_step(q)) == SQLITE_ROW) { const char *item = (const char *)sqlite3_column_text(q, 0); if (!item) { continue; /* a foreign turn with nothing this API can take */ } sqlite3_str_appendall(out, first ? "" : ","); sqlite3_str_appendall(out, item); first = 0; } sqlite3_finalize(q); sqlite3_str_appendall(out, "]"); if (step != SQLITE_DONE || sqlite3_str_errcode(out) != SQLITE_OK) { (void)snprintf(err, errcap, "could not build the request: %s", sqlite3_errmsg(s->db)); sqlite3_free(sqlite3_str_finish(out)); return NULL; } return sqlite3_str_finish(out); } static char *build_body(pic_store *s, const state *st, const char *messages, const char *tools) { const pic_compat *c = &st->model.compat; sqlite3_stmt *q = NULL; char *body = NULL; const char *fmt = c->thinking_format; int reasoning = st->model.reasoning; if (sqlite3_prepare_v2( s->db, "SELECT json_patch(json_object('model',?1,'messages',json(?2),'stream',json('true')," " 'tools',json((SELECT json_group_array(json_object('type','function','function',json_object(" " 'name',json_extract(value,'$.name'),'description',json_extract(value,'$.description')," " 'parameters',json(json_extract(value,'$.input_schema'))))) FROM json_each(?3))))," " json_object('stream_options',CASE WHEN ?4 THEN json_object('include_usage',json('true')) END," " 'store',CASE WHEN ?5 THEN json('false') END," " 'reasoning_effort',CASE WHEN ?6 AND ?7 = 'openai' AND ?8 THEN ?9 END," " 'reasoning',CASE WHEN ?6 AND ?7 = 'openrouter' THEN json_object('effort',?9) END," " 'thinking',CASE WHEN ?6 AND ?7 IN ('deepseek','zai') THEN json_object('type','enabled') END," " 'enable_thinking',CASE WHEN ?6 AND ?7 = 'qwen' THEN json('true') END))", -1, &q, NULL) != SQLITE_OK) { return NULL; } sqlite3_bind_text(q, 1, st->model.id, -1, SQLITE_STATIC); sqlite3_bind_text(q, 2, messages, -1, SQLITE_STATIC); sqlite3_bind_text(q, 3, tools, -1, SQLITE_STATIC); sqlite3_bind_int(q, 4, c->supports_usage_in_streaming); sqlite3_bind_int(q, 5, c->supports_store); sqlite3_bind_int(q, 6, reasoning); sqlite3_bind_text(q, 7, fmt, -1, SQLITE_STATIC); sqlite3_bind_int(q, 8, c->supports_reasoning_effort); sqlite3_bind_text(q, 9, REASONING_EFFORT, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) { body = pic_strdup((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); return body; } typedef struct { sqlite3 *db; pic_chat dec; pic_store *stream; /* replies only: deltas go to its events */ } decoding; static int dec_begin(void *ctx) { decoding *d = ctx; if (pic_chat_init(&d->dec, d->db) != 0) { return -1; } if (d->stream) { d->dec.on_delta = pic_ev_delta; d->dec.delta_ctx = d->stream; } return 0; } static int dec_finish(void *ctx, char *why, size_t cap) { decoding *d = ctx; if (pic_chat_finish(&d->dec) == 0) { return 0; } (void)snprintf(why, cap, "%s", d->dec.err); return -1; } static int dec_event(void *ctx, const char *event, const char *data, size_t len) { return pic_chat_event(&((decoding *)ctx)->dec, event, data, len); } static void dec_end(void *ctx) { pic_chat_free(&((decoding *)ctx)->dec); } static int chat_reply(pic_provider *p, pic_store *s, int64_t submission, int64_t turn, pic_reply *out, int *retryable, char *err, size_t errcap) { state *st = p->state; static const char *const extra[] = {"Accept: text/event-stream"}; decoding d; pic_stream_decoder dec = {dec_begin, dec_event, dec_finish, dec_end, &d}; char *messages = NULL, *body = NULL, request_id[128], *system_prompt = pic_session_text(s, submission, "system_prompt"), *tools = pic_session_text(s, submission, "tools"); int rc; (void)turn; *retryable = 0; memset(out, 0, sizeof *out); memset(&d, 0, sizeof d); d.db = s->db; d.stream = s; if (system_prompt) { messages = build_messages(s, st, submission, system_prompt, err, errcap); } body = messages && tools ? build_body(s, st, messages, tools) : NULL; sqlite3_free(messages); free(system_prompt); free(tools); if (!body) { if (!err[0]) { (void)snprintf(err, errcap, "could not build the request body"); } return -1; } rc = pic_stream_post(st->net, s, &st->model, st->url, PIC_AUTH_BEARER, extra, 1, body, &dec, request_id, sizeof request_id, retryable, err, errcap); free(body); if (rc != 0) { return -1; } out->native = pic_chat_native(&d.dec); out->neutral = pic_chat_neutral(&d.dec); out->stop_reason = pic_strdup(pic_chat_stop(&d.dec)); out->usage = d.dec.usage ? pic_strdup(d.dec.usage) : NULL; out->request_id = request_id[0] ? pic_strdup(request_id) : NULL; out->provider = pic_strdup(st->model.provider); out->api = pic_strdup(pic_api_name(st->model.api)); out->model = pic_strdup(st->model.id); dec_end(&d); if (!out->native || !out->neutral || !out->stop_reason || !out->provider || !out->api || !out->model) { pic_reply_free(out); (void)snprintf(err, errcap, "could not assemble the reply"); return -1; } return 0; } /* A plain request for compaction: SYSTEM and one USER message, no tools. */ static int chat_summarize(pic_provider *p, pic_store *s, const char *system, const char *user, char **text, char **usage, int *retryable, char *err, size_t errcap) { state *st = p->state; static const char *const extra[] = {"Accept: text/event-stream"}; decoding d; pic_stream_decoder dec = {dec_begin, dec_event, dec_finish, dec_end, &d}; char *body, *neutral; int rc; *text = *usage = NULL; memset(&d, 0, sizeof d); d.db = s->db; body = pic_json_body(s->db, "SELECT json_object('model',?1,'messages',json_array(json_object('role','system','content',?2),json_object('role','user','content',?3)),'stream',json('true'))", 3, st->model.id, system, user); if (!body) { (void)snprintf(err, errcap, "could not build the summary request"); return -1; } rc = pic_stream_post(st->net, s, &st->model, st->url, PIC_AUTH_BEARER, extra, 1, body, &dec, NULL, 0, retryable, err, errcap); free(body); if (rc != 0) { return -1; } /* A summary cut off at the token cap is incomplete: never a checkpoint. */ if (pic_chat_stop(&d.dec) && strcmp(pic_chat_stop(&d.dec), "length") == 0) { dec_end(&d); (void)snprintf(err, errcap, "the summary hit the token cap and is incomplete"); return -1; } neutral = pic_chat_neutral(&d.dec); *text = neutral ? pic_neutral_text(s->db, neutral) : NULL; *usage = d.dec.usage ? pic_strdup(d.dec.usage) : NULL; free(neutral); dec_end(&d); if (!*text) { (void)snprintf(err, errcap, "the summary reply had no text"); return -1; } return 0; } static void chat_free(pic_provider *p) { state *st = p->state; if (st) { pic_net_free(st->net); free(st->url); free(st->workspace); free(st); } p->state = NULL; } int pic_provider_chat_new(pic_provider *p, const pic_model *m, const char *url, const char *workspace, char *err, size_t errcap) { char endpoint[512]; state *st = calloc(1, sizeof *st); p->reply = chat_reply; p->summarize = chat_summarize; p->context_window = m->context_window; p->free = chat_free; p->state = st; if (!st) { (void)snprintf(err, errcap, "out of memory"); return -1; } st->model = *m; pic_model_url(m, endpoint, sizeof endpoint); if (!(st->url = pic_strdup(url ? url : endpoint)) || !(st->workspace = pic_strdup(workspace))) { (void)snprintf(err, errcap, "out of memory"); return -1; } st->net = pic_net_new(err, errcap); return st->net ? 0 : -1; }