aiden-duplex / code /duplex /tavily_search.py
sadmN's picture
Aiden duplex voice: code, checkpoint, base model, scripts
c74e524 verified
Raw History Blame Contribute Delete
2.78 kB
"""Bounded, cancellable Tavily requests for the live web-search tool."""
from __future__ import annotations
import asyncio
import re
from urllib.parse import urlsplit
import aiohttp
WEB_SEARCH = {'type': 'function', 'function': {
'name': 'web_search',
'description': 'Search the public web for requested or time-sensitive information.',
'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}},
'required': ['query']},
}}
def plain(value, length):
# Tool result strings are data, never Qwen protocol delimiters.
return re.sub(r'\s+', ' ', str(value or '')).strip()[:length].replace('<', '‹').replace('>', '›')
class TavilySearch:
def __init__(self, key):
self.key = key
async def __call__(self, query):
query = plain(query, 256)
failure = {'source': 'tavily', 'query': query, 'status': 'error'}
try:
timeout = aiohttp.ClientTimeout(total=12, connect=4)
payload = {'query': query, 'max_results': 3, 'search_depth': 'basic',
'include_answer': 'basic', 'include_raw_content': False}
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post('https://api.tavily.com/search', json=payload,
headers={'Authorization': f'Bearer {self.key}'},
allow_redirects=False) as response:
if response.status != 200:
return dict(failure, reason=f'HTTP {response.status}')
data = await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError):
return dict(failure, reason='Search service unavailable')
if not isinstance(data, dict) or not isinstance(data.get('results'), list):
return dict(failure, reason='Unexpected search response')
results = []
for row in (data.get('results') or [])[:3]:
if not isinstance(row, dict):
continue
url = plain(row.get('url'), 450)
try:
parsed = urlsplit(url)
except ValueError:
continue
if parsed.scheme not in ('https', 'http') or not parsed.netloc or parsed.username:
continue
results.append({'title': plain(row.get('title') or parsed.hostname, 140),
'url': url, 'excerpt': plain(row.get('content'), 420)})
if not results:
return dict(failure, status='no_match', reason='No usable sources returned')
return {'source': 'tavily', 'query': query, 'status': 'ok',
'answer': plain(data.get('answer'), 520), 'results': results}