Skip to content
pi-c Documentation
Login

Documentation

/* The provider's own web search: see websearch_native.h. */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "cred.h"
#include "model.h"
#include "perm.h"
#include "provider_http.h"
#include "userdb.h"
#include "websearch_native.h"

/* Providers with a search of their own: name, key variable, the declaration in the wire shape. */
static const struct {
    const char *provider, *api, *env, *native;
} wn_table[] = {
    {"anthropic", "anthropic-messages", "ANTHROPIC_API_KEY", "{\"type\":\"web_search_20250305\",\"name\":\"web_search\",\"max_uses\":5}"},
    {"openai", "openai-responses", "OPENAI_API_KEY", "{\"type\":\"web_search\"}"},
    {"xai", "openai-responses", "XAI_API_KEY", "{\"type\":\"web_search\"}"},
    {"openrouter", "openai-completions", "OPENROUTER_API_KEY", "{\"type\":\"openrouter:web_search\"}"},
};

static char *wn_text(sqlite3 *db, const char *sql, const char *a) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, a, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_type(q, 0) != SQLITE_NULL) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

char *pic_websearch_native(pic_store *s, int64_t submission, const pic_model *m, const char *tools, char **native) {
    char *has, *how, *session = NULL, mode[32], *rest = NULL;
    const char *decl = NULL;
    sqlite3_stmt *q = NULL;
    *native = NULL;
    for (size_t i = 0; i < sizeof wn_table / sizeof wn_table[0]; i++) {
        if (strcmp(m->provider, wn_table[i].provider) == 0 && strcmp(m->api, wn_table[i].api) == 0) {
            decl = wn_table[i].native;
        }
    }
    if (!decl) {
        return NULL;
    }
    if (strcmp(m->provider, "openai") == 0 &&
        pic_cred_source_of(m->provider, m->key_env, m->key_literal) == PIC_CRED_STORED_OAUTH) {
        return NULL; /* a ChatGPT sign-in: whether it may search is not known, so it gets the function */
    }
    has = wn_text(s->db, "SELECT 1 FROM json_each(?1) WHERE json_extract(value,'$.name') = 'web_search'", tools);
    if (!has) {
        return NULL;
    }
    free(has);
    how = pic_setting("webSearch");
    if ((how && strcmp(how, "brave") == 0) || pic_offline()) {
        free(how);
        return NULL;
    }
    free(how);
    if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, submission);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            session = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    if (pic_perm_get(s, session, mode, sizeof mode) != 0 || (strcmp(mode, "allow") != 0 && strcmp(mode, "ask-edits") != 0)) {
        free(session);
        return NULL;
    }
    free(session);
    rest = wn_text(s->db,
                   "SELECT coalesce(json_group_array(json(value)), '[]') FROM json_each(?1) WHERE json_extract(value,'$.name') IS NOT 'web_search'",
                   tools);
    if (!rest) {
        return NULL;
    }
    *native = strdup(decl);
    if (!*native) {
        free(rest);
        return NULL;
    }
    return rest;
}

char *pic_websearch_prepend(const char *tools, const char *native) {
    size_t n = strlen(tools), k = strlen(native);
    char *out = malloc(n + k + 4);
    const char *body = tools;
    if (!out) {
        return NULL;
    }
    while (*body == ' ') {
        body++;
    }
    body++; /* past the '[' */
    (void)snprintf(out, n + k + 4, "[%s%s%s", native, body[0] == ']' ? "" : ",", body);
    return out;
}

int pic_websearch_native_possible(void) {
    char *how = pic_setting("webSearch");
    int off = how && strcmp(how, "brave") == 0;
    free(how);
    if (off) {
        return 0;
    }
    for (size_t i = 0; i < sizeof wn_table / sizeof wn_table[0]; i++) {
        if (pic_cred_source_of(wn_table[i].provider, wn_table[i].env, "") != PIC_CRED_NONE) {
            return 1;
        }
    }
    return 0;
}

/* A request that does not declare the provider's search must not carry the search of an earlier
 * reply as server-tool blocks: the API would see results of a tool it was not given, beside a
 * function of the same name. Anthropic: the search and its results become two text blocks (the
 * query, the sources) and a text block loses its citations, which pointed into the results.
 * Responses: the search call goes, and with it the reasoning item that sits before it, which the API
 * takes only with the item it was followed by. */
char *pic_websearch_demote(sqlite3 *db, int anthropic, const char *json) {
    static const char anth[] =
        "SELECT json_group_array(json(m)) FROM (SELECT CASE WHEN json_extract(a.value,'$.role') = 'assistant'"
        " AND json_type(a.value,'$.content') = 'array' THEN json_set(a.value,'$.content',json((SELECT json_group_array(json(b)) FROM"
        "  (SELECT CASE json_extract(c.value,'$.type')"
        "   WHEN 'server_tool_use' THEN CASE WHEN json_extract(c.value,'$.name') = 'web_search' THEN json_object('type','text',"
        "     'text','Searched the web for: ' || coalesce(json_extract(c.value,'$.input.query'),'')) ELSE json(c.value) END"
        "   WHEN 'web_search_tool_result' THEN json_object('type','text','text',CASE json_type(c.value,'$.content')"
        "     WHEN 'array' THEN 'Sources:' || coalesce((SELECT group_concat(char(10) || (r.key + 1) || '. ' ||"
        "       coalesce(json_extract(r.value,'$.title'),'') || char(10) || '   ' || coalesce(json_extract(r.value,'$.url'),''), '')"
        "       FROM json_each(c.value,'$.content') r), '')"
        "     ELSE 'The search failed: ' || coalesce(json_extract(c.value,'$.content.error_code'),'an error') END)"
        "   WHEN 'text' THEN json_remove(c.value,'$.citations')"
        "   ELSE json(c.value) END AS b FROM json_each(a.value,'$.content') c ORDER BY c.key))))"
        "  ELSE json(a.value) END AS m FROM json_each(?1) a ORDER BY a.key)";
    static const char resp[] =
        "SELECT coalesce(json_group_array(json(v)),'[]') FROM (SELECT v FROM (SELECT value AS v, key AS k,"
        " json_extract(value,'$.type') AS t, lead(json_extract(value,'$.type')) OVER (ORDER BY key) AS nt FROM json_each(?1))"
        " WHERE t IS NOT 'web_search_call' AND NOT (t IS 'reasoning' AND nt IS 'web_search_call') ORDER BY k)";
    if (anthropic ? !strstr(json, "\"web_search_tool_result\"") && !strstr(json, "\"server_tool_use\"")
                  : !strstr(json, "\"web_search_call\"")) {
        return NULL;
    }
    return wn_text(db, anthropic ? anth : resp, json);
}