Skip to content
pi-c Artifact [021747873b]
Login

Artifact [021747873b]

Artifact 021747873b7491fb29c2e151f1410870eb45ae62e2440f1bf4cb1fa90aed4217:


/* 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\"}"},
    {"google", "google-generative-ai", "GEMINI_API_KEY", "{\"googleSearch\":{}}"},
};

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, "google") == 0 && strncmp(m->id, "gemini-3", 8) != 0) {
        return NULL; /* before Gemini 3, search cannot be combined with function declarations */
    }
    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;
}

void pic_json_strip_controls(char *j) {
    char *o = j;
    for (const char *p = j; *p;) {
        unsigned char c = (unsigned char)*p;
        if (c == '\\' && p[1] == 'u' && p[2] == '0' && p[3] == '0' && isxdigit((unsigned char)p[4]) && isxdigit((unsigned char)p[5])) {
            char hx[3] = {p[4], p[5], 0};
            int v = (int)strtol(hx, NULL, 16);
            if (v < 0x20 || (v >= 0x7f && v <= 0x9f)) {
                p += 6;
                continue;
            }
            memmove(o, p, 6);
            o += 6;
            p += 6;
        } else if (c == '\\' && p[1]) { /* an escape: the pair stays whole, so \\u001b is a backslash and text */
            o[0] = p[0];
            o[1] = p[1];
            o += 2;
            p += 2;
        } else if (c == 0x7f || (c == 0xc2 && (unsigned char)p[1] >= 0x80 && (unsigned char)p[1] <= 0x9f)) {
            p += c == 0x7f ? 1 : 2;
        } else {
            *o++ = *p++;
        }
    }
    *o = '\0';
}