API di risposta web_search
Utilizza la ricerca web ospitata con PHP cURL e decodifica in modo sicuro le risposte JSON o SSE.
API di risposta web_search
Usa l'hosted web_search strumento quando una risposta dipende dalle informazioni pubbliche attuali: versioni recenti, aggiornamenti della documentazione, prezzi, orari, normative, modifiche al prodotto o altri fatti che potrebbero essere cambiati dopo il periodo di formazione del modello.
Questa pagina descrive web_search SU POST /v1/responses. È diverso da quello autonomo `POST /v1/ricerca-web` punto finale.
Richiesta consigliata
Invia un array di input dell'API di risposta canonica. Richiedi lo strumento quando la risposta deve essere fondata su fonti live.
{
"model": "gpt-5.5",
"input": [
{
"role": "user",
"content": [
{
"type": "input_text",
"text": "Find the current stable PHP version. Use web search and cite the official sources."
}
]
}
],
"tools": [
{
"type": "web_search"
}
],
"tool_choice": "required",
"include": [
"web_search_call.action.sources"
],
"stream": false
}
Perché questi campi sono importanti
toolsrende disponibile la ricerca ospitata al modello.tool_choice: requiredimpedisce una risposta di sola memoria quando la verifica in tempo reale è obbligatoria.include: ["web_search_call.action.sources"]chiede all'API di includere gli URL considerati dalla chiamata di ricerca.stream: falserichiede una risposta non in streaming, ma i gateway compatibili possono comunque restituire un flusso di eventi di risposta. Il tuo client deve supportare entrambi i formati.
Non aggiungere parametri di generazione specifici del provider a meno che il modello selezionato non li supporti. I provider instradati possono rifiutare parametri come temperature, backgroundo controlli del token di output.
Esempio completo di cURL PHP
L'esempio seguente invia la richiesta, preserva il corpo dell'errore upstream e decodifica una normale risposta JSON o una risposta agli eventi inviati dal server.
<?php
declare(strict_types=1);
$baseUrl = 'https://api.model-gate.com';
$apiKey = getenv('MODEL_GATE_API_KEY') ?: '';
if ($apiKey === '') {
throw new RuntimeException('MODEL_GATE_API_KEY is not configured.');
}
$url = rtrim($baseUrl, '/') . '/v1/responses';
$request = [
'model' => 'gpt-5.5',
'input' => [[
'role' => 'user',
'content' => [[
'type' => 'input_text',
'text' => 'Find the current stable PHP version. '
. 'Use web search and cite official sources.',
]],
]],
'tools' => [[
'type' => 'web_search',
]],
'tool_choice' => 'required',
'include' => [
'web_search_call.action.sources',
],
'stream' => false,
];
$json = json_encode(
$request,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
$responseHeaders = [];
$ch = curl_init($url);
if ($ch === false) {
throw new RuntimeException('Unable to initialize cURL.');
}
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 15,
CURLOPT_TIMEOUT => 900,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
'Accept: application/json, text/event-stream',
],
CURLOPT_POSTFIELDS => $json,
CURLOPT_HEADERFUNCTION => static function ($ch, string $line) use (&$responseHeaders): int {
$length = strlen($line);
$line = trim($line);
if ($line === '' || !str_contains($line, ':')) {
return $length;
}
[$name, $value] = array_map('trim', explode(':', $line, 2));
$responseHeaders[strtolower($name)] = $value;
return $length;
},
]);
$responseBody = curl_exec($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErrorNumber = curl_errno($ch);
$curlError = curl_error($ch);
curl_close($ch);
if ($responseBody === false) {
throw new RuntimeException(
sprintf('cURL error %d: %s', $curlErrorNumber, $curlError)
);
}
if ($httpCode < 200 || $httpCode >= 300) {
// Keep the exact upstream body. It usually contains the parameter or model error.
throw new RuntimeException(
"API returned HTTP {$httpCode}: {$responseBody}"
);
}
$response = decodeResponsesBody(
$responseBody,
$responseHeaders['content-type'] ?? ''
);
$text = '';
$sources = [];
$searchCalls = 0;
foreach (($response['output'] ?? []) as $item) {
if (($item['type'] ?? null) === 'web_search_call') {
$searchCalls++;
foreach (($item['action']['sources'] ?? []) as $source) {
$url = trim((string) ($source['url'] ?? ''));
if ($url !== '') {
$sources[$url] = $url;
}
}
}
if (($item['type'] ?? null) !== 'message') {
continue;
}
foreach (($item['content'] ?? []) as $part) {
if (($part['type'] ?? null) !== 'output_text') {
continue;
}
$text .= (string) ($part['text'] ?? '');
foreach (($part['annotations'] ?? []) as $annotation) {
if (($annotation['type'] ?? null) !== 'url_citation') {
continue;
}
$url = trim((string) ($annotation['url'] ?? ''));
if ($url !== '') {
$sources[$url] = $url;
}
}
}
}
if ($searchCalls === 0) {
throw new RuntimeException('The response did not contain web_search_call.');
}
if ($sources === []) {
throw new RuntimeException('The response did not contain auditable source URLs.');
}
echo $text . PHP_EOL;
echo "Sources:" . PHP_EOL;
foreach ($sources as $sourceUrl) {
echo '- ' . $sourceUrl . PHP_EOL;
}
function decodeResponsesBody(string $body, string $contentType): array
{
$trimmed = ltrim($body);
$looksLikeSse = str_contains(strtolower($contentType), 'text/event-stream')
|| str_starts_with($trimmed, 'event:')
|| str_starts_with($trimmed, 'data:');
if (!$looksLikeSse) {
$decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if (!is_array($decoded)) {
throw new RuntimeException('Responses API returned a non-object JSON value.');
}
return $decoded;
}
return decodeResponsesSse($body);
}
function decodeResponsesSse(string $body): array
{
$output = [];
$completedResponse = [];
$eventName = '';
$dataLines = [];
$flush = static function () use (&$eventName, &$dataLines, &$output, &$completedResponse): void {
if ($dataLines === []) {
$eventName = '';
return;
}
$rawData = implode("\n", $dataLines);
$dataLines = [];
if ($rawData === '[DONE]') {
$eventName = '';
return;
}
$event = json_decode($rawData, true, 512, JSON_THROW_ON_ERROR);
$type = (string) ($event['type'] ?? $eventName);
if ($type === 'response.output_item.done' && is_array($event['item'] ?? null)) {
$output[] = $event['item'];
}
if ($type === 'response.completed' && is_array($event['response'] ?? null)) {
$completedResponse = $event['response'];
}
$eventName = '';
};
foreach (preg_split('/\r\n|\r|\n/', $body) ?: [] as $line) {
if ($line === '') {
$flush();
continue;
}
if (str_starts_with($line, 'event:')) {
$eventName = trim(substr($line, 6));
continue;
}
if (str_starts_with($line, 'data:')) {
$dataLines[] = ltrim(substr($line, 5));
}
}
$flush();
if ($completedResponse === [] && $output === []) {
throw new RuntimeException('No completed Responses API event was found.');
}
// Some compatible gateways send an empty output array in response.completed.
// Preserve the completed metadata but reconstruct output from output_item.done events.
$completedResponse['output'] = $output !== []
? $output
: ($completedResponse['output'] ?? []);
return $completedResponse;
}
Importante: stream: false potrebbe ancora restituire SSE
stream: false esprime la modalità di risposta richiesta. Un proxy compatibile o instradato a monte può comunque serializzare il ciclo di vita delle risposte completato come text/event-stream con eventi come:
event: response.output_item.done
data: {"type":"response.output_item.done","item":{"type":"web_search_call",...}}
event: response.completed
data: {"type":"response.completed","response":{"status":"completed",...}}
Non correre json_decode() direttamente sull'intero corpo finché non hai determinato se si tratta di JSON o SSE. Per SSE, raccolta completata response.output_item.done elementi e il finale response.completed metadati.
Convalida della fonte
Per i flussi di lavoro con informazioni correnti, convalidare tutto quanto segue prima di accettare la risposta:
- Almeno uno completato
web_search_callesiste. - Esiste almeno un URL in
web_search_call.action.sourceso unoutput_textCitazione dell'URL. - Lo stato della risposta finale è
completed. - Le fonti supportano le affermazioni che intendi utilizzare.
- I fatti importanti sono preferibilmente confermati da una fonte ufficiale o primaria.
Non considerare una risposta fluente come prova che la ricerca è stata eseguita. Controllare l'output dello strumento a livello di codice.
Gestione degli errori e tentativi
- Conserva i corpi delle risposte non 2xx. Contengono utili messaggi di convalida del provider.
- Non riprovare HTTP
400senza modificare la richiesta respinta. - Riprova transitorio
429,502,503,504e guasti di trasporto con backoff e jitter esponenziali. - Utilizza una chiave di idempotenza nella tua applicazione quando un nuovo tentativo potrebbe attivare un'azione aziendale.
- Mantieni allineati i timeout di applicazione, PHP, proxy inverso e gateway per richieste di ricerca lunghe.
- Non esporre mai le chiavi API o i payload grezzi acquisiti agli utenti finali.