/* The provider's own web search: see websearch_native.h. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1 /* strdup and the rest of POSIX under -std=c11 on glibc */
#endif
#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 "stripctl.h"
#include "toolreg.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\":{}}"},
};
/* Gemini mixes Google Search with function tools from Gemini 3 on: "gemini-N..." with N at least 3. */
static int wn_gemini3(const char *id) {
const char *p = strncmp(id, "models/", 7) == 0 ? id + 7 : id;
return strncmp(p, "gemini-", 7) == 0 && isdigit((unsigned char)p[7]) && atoi(p + 7) >= 3;
}
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;
}
/* The declaration of M's provider's own search, or NULL when M cannot use one: no table entry, a
* Gemini before 3, or a ChatGPT sign-in (whether it may search is not known, so it gets the
* function), or the setting
* webSearch says brave, or offline is on. */
static const char *wn_declaration(const pic_model *m) {
const char *decl = NULL;
char *how;
int off;
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 || (strcmp(m->provider, "openai") == 0 &&
pic_cred_source_of(m->provider, m->key_env, m->key_literal) == PIC_CRED_STORED_OAUTH) ||
(strcmp(m->provider, "google") == 0 && !wn_gemini3(m->id))) {
return NULL;
}
how = pic_setting("webSearch");
off = (how && strcmp(how, "brave") == 0) || pic_offline();
free(how);
return off ? NULL : decl;
}
char *pic_websearch_native(pic_store *s, int64_t submission, const pic_model *m, const char *tools, char **native) {
char *has, *session = NULL, mode[32], *rest = NULL;
const char *decl = wn_declaration(m);
sqlite3_stmt *q = NULL;
*native = NULL;
if (!decl) {
return NULL;
}
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);
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;
}
/* 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.
* (A Responses turn is not rewritten here: its adapter sends it in the form a model switch uses.) */
char *pic_websearch_demote(sqlite3 *db, 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: ' || pic_strip(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) || '. ' ||"
" pic_strip(coalesce(json_extract(r.value,'$.title'),'')) || char(10) || ' ' ||"
" pic_strip(coalesce(json_extract(r.value,'$.url'),'')), '')"
" FROM json_each(c.value,'$.content') r), '')"
" ELSE 'The search failed: ' || pic_strip(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)";
if (!strstr(json, "\"web_search_tool_result\"") && !strstr(json, "\"server_tool_use\"")) {
return NULL;
}
(void)pic_strip_register(db);
return wn_text(db, anth, json);
}