/* OpenAI Responses adapter: input items built from the journal as Pi's
* openai-responses adapter builds them, streamed through the shared POST and
* the item decoder. Reasoning items go back whole, encrypted_content
* included, so a reasoning model keeps its reasoning with store:false. The
* API takes 50MB a request, over pic.h's request image budget. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cred.h"
#include "openai_responses.h"
#include "provider_http.h"
typedef struct {
pic_model model;
char *url, *workspace;
pic_net *net;
} pre_state;
/* Appends the elements of a JSON array (its text between the brackets). */
static void splice_items(sqlite3_str *out, const char *array, int *first) {
size_t n = strlen(array);
if (n < 2 || array[0] != '[') {
return;
}
while (n > 0 && array[n - 1] != ']') {
n--;
}
if (n <= 2) {
return; /* empty */
}
sqlite3_str_appendall(out, *first ? "" : ",");
sqlite3_str_append(out, array + 1, (int)(n - 2));
*first = 0;
}
/* The input items: the system prompt; the user's text; each assistant turn
* (its own items verbatim to its own model, else rebuilt from the neutral
* form: an assistant message for its text and a function_call per tool call,
* no reasoning); each tool result as a function_call_output. Rows that hold
* several items come back as a JSON array with splice = 1. */
static char *build_input(pic_store *s, const pre_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);
int step, first = 1;
if (sqlite3_prepare_v2(
s->db,
PIC_CONTEXT_CTE "SELECT CASE e.kind WHEN 'user' THEN 0 WHEN 'tool_result' THEN 0 WHEN 'instructions' THEN 0 WHEN 'hook' THEN 0 WHEN 'compaction' THEN 0 WHEN 'branch_summary' THEN 0 ELSE 1 END,"
" CASE e.kind"
" WHEN 'instructions' THEN json_object('role',?5,'content',"
" '<project_instructions_update>' || char(10) || e.body || char(10) || '</project_instructions_update>')"
" WHEN 'hook' THEN json_object('role','user','content',json_array(json_object('type','input_text','text',e.body)))"
" WHEN 'user' THEN json_object('role','user','content',coalesce(json(pic_content(e.seq,e.body,'responses-user',?6,?9)),"
" json_array(json_object('type','input_text','text',e.body))))"
" WHEN 'compaction' THEN json_object('role','user','content',json_array(json_object('type','input_text','text',"
PIC_SUMMARY_SQL("e.body") ")))"
" WHEN 'branch_summary' THEN json_object('role','user','content',json_array(json_object('type','input_text','text',"
PIC_BRANCH_SUMMARY_SQL("e.body") ")))"
" WHEN 'tool_result' THEN json_object('type','function_call_output','call_id',"
" CASE WHEN a.seq > kk.cseq AND a.provider IS ?2 AND a.api IS ?3 AND a.model IS ?4"
" THEN CASE WHEN instr(f.call_id,'|') > 0 THEN substr(f.call_id,1,instr(f.call_id,'|')-1) ELSE f.call_id END"
" ELSE pic_norm_id(f.call_id,'openai-responses',?2) END,"
" 'output',coalesce(json(pic_content(e.seq,e.body,'responses-tool',?6,?9)),e.body))"
" ELSE CASE WHEN v.fresh AND e.provider IS ?2 AND e.api IS ?3 AND e.model IS ?4 THEN e.native"
" ELSE (SELECT coalesce(json_group_array(json(y)),'[]') FROM (SELECT 0 AS o, json_object('role','assistant',"
" 'content',(SELECT group_concat(json_extract(value,'$.text'),'') FROM json_each(e.body)"
" WHERE json_extract(value,'$.type')='text')) AS y"
" WHERE EXISTS (SELECT 1 FROM json_each(e.body) WHERE json_extract(value,'$.type')='text'"
" AND json_extract(value,'$.text') != '')"
" UNION ALL SELECT 1 + key, json_object('type','function_call','call_id',"
" pic_norm_id(json_extract(value,'$.id'),'openai-responses',?2),'name',json_extract(value,'$.name'),"
" 'arguments',json_extract(value,'$.arguments') || '')"
" FROM json_each(e.body) WHERE json_extract(value,'$.type')='toolCall' ORDER BY o)) 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, st->model.api, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 4, st->model.id, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 5, st->model.reasoning && st->model.compat.supports_developer_role ? "developer" : "system", -1,
SQLITE_STATIC);
sqlite3_bind_int(q, 6, st->model.image_input);
sqlite3_bind_int64(q, 9, pic_image_budget(s, submission));
sqlite3_str_appendall(out, "[");
{
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 && st->model.compat.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, (const char *)sqlite3_column_text(sp, 0));
first = 0;
}
sqlite3_finalize(sp);
}
}
while ((step = sqlite3_step(q)) == SQLITE_ROW) {
const char *item = (const char *)sqlite3_column_text(q, 1);
if (!item) {
continue;
}
if (sqlite3_column_int(q, 0)) {
splice_items(out, item, &first);
} else {
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 *pre_build_body(pic_store *s, const pre_state *st, const char *level, const char *input, const char *tools,
const char *session) {
sqlite3_stmt *q = NULL;
pic_cache retention = pic_cache_retention();
int key = retention != PIC_CACHE_NONE && session,
/* A subscription's token (Pi's Sign in with ChatGPT) is refused with prompt_cache_retention. */
ttl24 = retention == PIC_CACHE_LONG && st->model.compat.supports_long_cache &&
pic_cred_source_of(st->model.provider, st->model.key_env, st->model.key_literal) != PIC_CRED_STORED_OAUTH;
char *body = NULL;
const char *off_value = NULL;
int on = strcmp(level, "off") != 0, off_state = pic_model_thinking_map(&st->model, "off", &off_value);
if (sqlite3_prepare_v2(
s->db,
"SELECT CASE WHEN json_array_length(?3) = 0 THEN json_remove(b,'$.tools') ELSE b END FROM (SELECT json_patch(json_object('model',?1,'input',json(?2),'stream',json('true'),'store',json('false'),"
" 'tools',json((SELECT json_group_array(json_object('type','function','name',json_extract(value,'$.name'),"
" 'description',json_extract(value,'$.description'),'parameters',json(json_extract(value,'$.input_schema'))))"
" FROM json_each(?3)))),"
" json_object('prompt_cache_key',CASE WHEN ?10 THEN substr(?11,1,64) END,"
" 'prompt_cache_retention',CASE WHEN ?12 THEN '24h' END,"
" 'include',CASE WHEN ?4 AND (?6 OR ?9 = 'xai') THEN json_array('reasoning.encrypted_content') END,"
" 'reasoning',CASE WHEN ?4 AND ?6 THEN json_object('effort',?5,'summary','auto')"
" WHEN ?4 AND ?7 != 1 THEN json_object('effort',coalesce(?8,'none')) END)) AS b)",
-1, &q, NULL) != SQLITE_OK) {
return NULL;
}
sqlite3_bind_text(q, 1, st->model.id, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 2, input, -1, SQLITE_STATIC);
sqlite3_bind_text(q, 3, tools, -1, SQLITE_STATIC);
sqlite3_bind_int(q, 4, st->model.reasoning);
if (on) {
sqlite3_bind_text(q, 5, pic_model_thinking_effort(&st->model, level), -1, SQLITE_STATIC);
}
sqlite3_bind_int(q, 6, on);
sqlite3_bind_int(q, 7, off_state);
sqlite3_bind_int(q, 10, key);
sqlite3_bind_text(q, 11, session ? session : "", -1, SQLITE_STATIC);
sqlite3_bind_int(q, 12, ttl24);
if (off_state == 2) {
sqlite3_bind_text(q, 8, off_value, -1, SQLITE_STATIC);
}
sqlite3_bind_text(q, 9, st->model.provider, -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_responses dec;
pic_store *stream; /* replies only: deltas go to its events */
} decoding;
static int dec_begin(void *ctx) {
decoding *d = ctx;
return pic_responses_init(&d->dec, d->db);
}
static int dec_event(void *ctx, const char *event, const char *data, size_t len) {
decoding *d = ctx;
/* Text and reasoning deltas, for live events; the reply is built from
* whole output items. */
if (d->stream && d->stream->events && event &&
(strcmp(event, "response.output_text.delta") == 0 || strcmp(event, "response.reasoning_summary_text.delta") == 0 ||
strcmp(event, "response.reasoning_text.delta") == 0)) {
sqlite3_stmt *q = NULL;
if (sqlite3_prepare_v2(d->db, "SELECT json_extract(?1, '$.delta') WHERE json_valid(?1)", -1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, data, (int)len, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) == SQLITE_TEXT) {
pic_ev_delta(d->stream, strcmp(event, "response.output_text.delta") != 0,
(const char *)sqlite3_column_text(q, 0), (size_t)sqlite3_column_bytes(q, 0));
}
sqlite3_finalize(q);
}
}
return pic_responses_event(&((decoding *)ctx)->dec, event, data, len);
}
static int dec_finish(void *ctx, char *why, size_t cap) {
decoding *d = ctx;
if (pic_responses_finish(&d->dec) == 0) {
return 0;
}
(void)snprintf(why, cap, "%s", d->dec.err);
return -1;
}
static void dec_end(void *ctx) { pic_responses_free(&((decoding *)ctx)->dec); }
static int responses_reply(pic_provider *p, pic_store *s, int64_t submission, int64_t turn, pic_reply *out,
int *retryable, char *err, size_t errcap) {
pre_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 *input = NULL, *body = NULL, request_id[128], *system_prompt = pic_session_text(s, submission, "system_prompt"),
*tools = pic_session_text(s, submission, "tools"), *session = pic_session_id(s, submission);
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) {
input = build_input(s, st, submission, system_prompt, err, errcap);
}
body = input && tools ? pre_build_body(s, st, p->thinking, input, tools, session) : NULL;
sqlite3_free(input);
free(session);
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_responses_native(&d.dec);
out->neutral = pic_responses_neutral(&d.dec);
out->stop_reason = pic_strdup(pic_responses_stop(&d.dec));
out->usage = d.dec.usage ? pic_strdup(d.dec.usage) : NULL;
out->request_id = request_id[0] ? pic_strdup(request_id) : d.dec.response_id ? pic_strdup(d.dec.response_id) : NULL;
out->provider = pic_strdup(st->model.provider);
out->api = pic_strdup(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 responses_summarize(pic_provider *p, pic_store *s, const char *system, const char *user, char **text,
char **usage, int *retryable, char *err, size_t errcap) {
pre_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,'input',json_array(json_object('role','system','content',?2),json_object('role','user','content',json_array(json_object('type','input_text','text',?3)))),'stream',json('true'),'store',json('false'))", 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_responses_stop(&d.dec) && strcmp(pic_responses_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_responses_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 responses_free(pic_provider *p) {
pre_state *st = p->state;
if (st) {
pic_net_free(st->net);
free(st->url);
free(st->workspace);
free(st);
}
p->state = NULL;
}
static int responses_open(pic_provider *p, const pic_model *m, const char *url, const char *workspace, char *err,
size_t errcap) {
char endpoint[512];
pre_state *st = calloc(1, sizeof *st);
p->reply = responses_reply;
p->summarize = responses_summarize;
p->context_window = m->context_window;
p->free = responses_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;
}
/* Long retention is prompt_cache_retention of 24 hours. */
static long responses_cache_long(const pic_model *m) {
(void)m;
return 86400;
}
/* [A-Za-z0-9_-], at most 64, and no trailing '_'. */
static void responses_norm_id(char *buf, size_t cap, const char *id, const char *provider) {
size_t n;
(void)cap;
(void)id;
(void)provider;
pic_id_sanitize(buf);
if (strlen(buf) > 64) {
buf[64] = '\0';
}
for (n = strlen(buf); n > 0 && buf[n - 1] == '_'; n--) {
buf[n - 1] = '\0';
}
}
static void responses_image(sqlite3_str *out, const char *mime, const char *data) {
sqlite3_str_appendf(out, "{\"type\":\"input_image\",\"detail\":\"auto\",\"image_url\":\"data:%s;base64,%s\"}", mime, data);
}
/* responses-user: the blocks; responses-tool: the text and the images while
* an image is left, else the text joined. */
static const pic_content_shape responses_shapes[] = {
{"responses-user", PIC_SHAPE_BLOCKS, 0, 0, 0, 0, "input_text", responses_image},
{"responses-tool", PIC_SHAPE_TEXT_IMAGES, 1, 0, 0, 0, "input_text", responses_image},
};
/* A free check: the models list says the key is valid or refused; an exhausted
* quota shows only on use. */
static void responses_probe_request(const pic_model *m, pic_probe_request *req) {
(void)m;
(void)snprintf(req->path, sizeof req->path, "/models");
req->auth = PIC_AUTH_BEARER;
}
static const pic_provider_probe responses_probe = {responses_probe_request, NULL};
const pic_provider_adapter pic_responses_adapter = {
"openai-responses", responses_open, responses_cache_long, responses_norm_id,
responses_shapes, sizeof responses_shapes / sizeof responses_shapes[0], &responses_probe,
};