Веб-поиск
Интеграция веб-поиска в реальном времени с Responses API
Responses API поддерживает интеграцию веб-поиска, позволяя моделям получать доступ к информации в реальном времени из интернета и предоставлять ответы с правильными цитатами и аннотациями.
Плагин веб-поиска
Включите веб-поиск, используя параметр plugins
:
typescript
const response = await fetch('https://api.aitunnel.ru/v1/responses', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o',
input: 'Какая сейчас погода в Москве?',
plugins: [{ id: 'web', max_results: 3 }],
max_output_tokens: 9000,
}),
});
const result = await response.json();
console.log(result);
python
import requests
response = requests.post(
'https://api.aitunnel.ru/v1/responses',
headers={
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
json={
'model': 'gpt-4o',
'input': 'Какая сейчас погода в Москве?',
'plugins': [{'id': 'web', 'max_results': 3}],
'max_output_tokens': 9000,
}
)
result = response.json()
print(result)
bash
curl -X POST https://api.aitunnel.ru/v1/responses \
-H "Authorization: Bearer sk-aitunnel-xxx" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"input": "Какая сейчас погода в Москве?",
"plugins": [{"id": "web", "max_results": 3}],
"max_output_tokens": 9000
}'
Конфигурация плагина
Настройте поведение веб-поиска:
Параметр | Тип | Описание |
---|---|---|
id | string | Обязательно. Должен быть "web" |
max_results | integer | Максимальное количество результатов поиска (1-10) |
Структурированные сообщения с веб-поиском
Используйте структурированные сообщения для более сложных запросов:
typescript
const response = await fetch('https://api.aitunnel.ru/v1/responses', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o',
input: [
{
type: 'message',
role: 'user',
content: [
{
type: 'input_text',
text: 'Какие позитивные новости были сегодня?',
},
],
},
],
plugins: [{ id: 'web', max_results: 2 }],
max_output_tokens: 9000,
}),
});
const result = await response.json();
console.log(result);
python
response = requests.post(
'https://api.aitunnel.ru/v1/responses',
headers={
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
json={
'model': 'gpt-4o',
'input': [
{
'type': 'message',
'role': 'user',
'content': [
{
'type': 'input_text',
'text': 'Какие позитивные новости были сегодня?',
},
],
},
],
'plugins': [{'id': 'web', 'max_results': 2}],
'max_output_tokens': 9000,
}
)
result = response.json()
print(result)
Ответ с аннотациями
Ответы веб-поиска включают аннотации с цитатами:
json
{
"id": "resp_1234567890",
"object": "response",
"created_at": 1234567890,
"model": "gpt-4o",
"output": [
{
"type": "message",
"id": "msg_abc123",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Сегодня в Москве облачная погода с температурой +15°C. Ожидается небольшой дождь во второй половине дня. Влажность воздуха составляет 65%, ветер западный 3-5 м/с. Завтра температура поднимется до +18°C с переменной облачностью.",
"annotations": [
{
"type": "url_citation",
"url": "https://weather.com/moscow",
"start_index": 0,
"end_index": 85
},
{
"type": "url_citation",
"url": "https://gismeteo.ru/weather-moscow",
"start_index": 150,
"end_index": 200
}
]
}
]
}
],
"usage": {
"input_tokens": 12,
"output_tokens": 45,
"total_tokens": 57
},
"status": "completed"
}
Типы аннотаций
Веб-поиск возвращает различные типы аннотаций:
URL-цитирование
json
{
"type": "url_citation",
"url": "https://example.com/article",
"start_index": 0,
"end_index": 50
}
type
: Всегда "url_citation"url
: URL источникаstart_index
: Начальный индекс цитируемого текстаend_index
: Конечный индекс цитируемого текста
Сложные поисковые запросы
Обрабатывайте многокомпонентные поисковые запросы:
typescript
const response = await fetch('https://api.aitunnel.ru/v1/responses', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o',
input: [
{
type: 'message',
role: 'user',
content: [
{
type: 'input_text',
text: 'Сравни последние модели OpenAI и Anthropic',
},
],
},
],
plugins: [{ id: 'web', max_results: 5 }],
max_output_tokens: 9000,
}),
});
const result = await response.json();
console.log(result);
python
response = requests.post(
'https://api.aitunnel.ru/v1/responses',
headers={
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
json={
'model': 'gpt-4o',
'input': [
{
'type': 'message',
'role': 'user',
'content': [
{
'type': 'input_text',
'text': 'Сравни последние модели OpenAI и Anthropic',
},
],
},
],
'plugins': [{'id': 'web', 'max_results': 5}],
'max_output_tokens': 9000,
}
)
result = response.json()
print(result)
Веб-поиск в разговоре
Включайте веб-поиск в многоходовые разговоры:
typescript
const response = await fetch('https://api.aitunnel.ru/v1/responses', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o',
input: [
{
type: 'message',
role: 'user',
content: [
{
type: 'input_text',
text: 'Какая последняя версия React?',
},
],
},
{
type: 'message',
id: 'msg_1',
status: 'completed',
role: 'assistant',
content: [
{
type: 'output_text',
text: 'Позвольте мне найти информацию о последней версии React.',
annotations: [],
},
],
},
{
type: 'message',
role: 'user',
content: [
{
type: 'input_text',
text: 'Да, пожалуйста, найди самую свежую информацию',
},
],
},
],
plugins: [{ id: 'web', max_results: 2 }],
max_output_tokens: 9000,
}),
});
const result = await response.json();
console.log(result);
python
response = requests.post(
'https://api.aitunnel.ru/v1/responses',
headers={
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
json={
'model': 'gpt-4o',
'input': [
{
'type': 'message',
'role': 'user',
'content': [
{
'type': 'input_text',
'text': 'Какая последняя версия React?',
},
],
},
{
'type': 'message',
'id': 'msg_1',
'status': 'completed',
'role': 'assistant',
'content': [
{
'type': 'output_text',
'text': 'Позвольте мне найти информацию о последней версии React.',
'annotations': [],
},
],
},
{
'type': 'message',
'role': 'user',
'content': [
{
'type': 'input_text',
'text': 'Да, пожалуйста, найди самую свежую информацию',
},
],
},
],
'plugins': [{'id': 'web', 'max_results': 2}],
'max_output_tokens': 9000,
}
)
result = response.json()
print(result)
Стриминговый веб-поиск
Отслеживайте прогресс веб-поиска со стримингом:
typescript
const response = await fetch('https://api.aitunnel.ru/v1/responses', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o',
input: [
{
type: 'message',
role: 'user',
content: [
{
type: 'input_text',
text: 'Какие последние новости об ИИ?',
},
],
},
],
plugins: [{ id: 'web', max_results: 2 }],
stream: true,
max_output_tokens: 9000,
}),
});
const reader = response.body?.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader!.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') return;
try {
const parsed = JSON.parse(data);
if (parsed.type === 'response.output_item.added' &&
parsed.item?.type === 'message') {
console.log('Сообщение добавлено');
}
if (parsed.type === 'response.completed') {
const annotations = parsed.response?.output
?.find(o => o.type === 'message')
?.content?.find(c => c.type === 'output_text')
?.annotations || [];
console.log('Цитаты:', annotations.length);
}
} catch (e) {
// Пропускаем невалидный JSON
}
}
}
}
python
import requests
import json
response = requests.post(
'https://api.aitunnel.ru/v1/responses',
headers={
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
json={
'model': 'gpt-4o',
'input': [
{
'type': 'message',
'role': 'user',
'content': [
{
'type': 'input_text',
'text': 'Какие последние новости об ИИ?',
},
],
},
],
'plugins': [{'id': 'web', 'max_results': 2}],
'stream': True,
'max_output_tokens': 9000,
},
stream=True
)
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data = line[6:]
if data == '[DONE]':
break
try:
parsed = json.loads(data)
if (parsed.get('type') == 'response.output_item.added' and
parsed.get('item', {}).get('type') == 'message'):
print('Сообщение добавлено')
if parsed.get('type') == 'response.completed':
output = parsed.get('response', {}).get('output', [])
message = next((o for o in output if o.get('type') == 'message'), {})
content = message.get('content', [])
text_content = next((c for c in content if c.get('type') == 'output_text'), {})
annotations = text_content.get('annotations', [])
print(f'Цитаты: {len(annotations)}')
except json.JSONDecodeError:
continue
Обработка аннотаций
Извлекайте и обрабатывайте информацию о цитатах:
typescript
function extractCitations(response: any) {
const messageOutput = response.output?.find((o: any) => o.type === 'message');
const textContent = messageOutput?.content?.find((c: any) => c.type === 'output_text');
const annotations = textContent?.annotations || [];
return annotations
.filter((annotation: any) => annotation.type === 'url_citation')
.map((annotation: any) => ({
url: annotation.url,
text: textContent.text.slice(annotation.start_index, annotation.end_index),
startIndex: annotation.start_index,
endIndex: annotation.end_index,
}));
}
const result = await response.json();
const citations = extractCitations(result);
console.log('Найденные цитаты:', citations);
python
def extract_citations(response_data):
"""Извлечь цитаты из ответа"""
output = response_data.get('output', [])
message_output = next((o for o in output if o.get('type') == 'message'), {})
content = message_output.get('content', [])
text_content = next((c for c in content if c.get('type') == 'output_text'), {})
annotations = text_content.get('annotations', [])
citations = []
for annotation in annotations:
if annotation.get('type') == 'url_citation':
start_idx = annotation.get('start_index', 0)
end_idx = annotation.get('end_index', 0)
citations.append({
'url': annotation.get('url'),
'text': text_content.get('text', '')[start_idx:end_idx],
'start_index': start_idx,
'end_index': end_idx,
})
return citations
# Использование
result = response.json()
citations = extract_citations(result)
print(f'Найденные цитаты: {citations}')
Примеры использования
Актуальные новости
python
response = requests.post(
'https://api.aitunnel.ru/v1/responses',
headers={
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
json={
'model': 'gpt-4o',
'input': 'Какие основные события произошли в мире технологий на этой неделе?',
'plugins': [{'id': 'web', 'max_results': 4}],
}
)
Исследование продуктов
python
response = requests.post(
'https://api.aitunnel.ru/v1/responses',
headers={
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
json={
'model': 'gpt-4o',
'input': 'Какие лучшие ноутбуки для программирования в 2024 году по соотношению цена-качество?',
'plugins': [{'id': 'web', 'max_results': 6}],
}
)
Научные исследования
python
response = requests.post(
'https://api.aitunnel.ru/v1/responses',
headers={
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
json={
'model': 'gpt-4o',
'input': 'Какие прорывы в медицине и лечении рака произошли в 2024 году?',
'plugins': [{'id': 'web', 'max_results': 5}],
}
)
Лучшие практики
- Ограничивайте результаты: Используйте подходящий
max_results
для баланса качества и скорости - Обрабатывайте аннотации: Обрабатывайте аннотации цитат для правильного указания источников
- Специфичность запросов: Делайте поисковые запросы конкретными для лучших результатов
- Обработка ошибок: Обрабатывайте случаи, когда веб-поиск может не сработать
- Лимиты скорости: Учитывайте лимиты скорости поиска
Ограничения
- Максимум 10 результатов поиска на запрос
- Поиск может увеличить время ответа на 3-10 секунд
- Качество результатов зависит от доступности и актуальности веб-контента
- Некоторые сайты могут быть недоступны для поиска
Комбинирование с другими возможностями
Веб-поиск можно комбинировать с рассуждениями и инструментами:
python
response = requests.post(
'https://api.aitunnel.ru/v1/responses',
headers={
'Authorization': 'Bearer sk-aitunnel-xxx',
'Content-Type': 'application/json',
},
json={
'model': 'o1-preview',
'input': 'Проанализируй текущую ситуацию на рынке недвижимости в Москве и предскажи тенденции на следующий год',
'plugins': [{'id': 'web', 'max_results': 5}],
'reasoning': {'effort': 'high'},
}
)
Следующие шаги
- Изучите интеграцию Вызова инструментов
- Исследуйте возможности Рассуждений
- Просмотрите основы Базового использования