@@ -22,30 +22,42 @@ async def brave_search(query: str, limit: int = 10) -> dict | None:
2222 headers = {"X-Subscription-Token" : api_key }
2323 params = {"q" : query , "count" : limit }
2424
25- try :
26- async with httpx .AsyncClient () as client :
27- r = await client .get (url , headers = headers , params = params , timeout = 10 )
28- r .raise_for_status ()
29- results = r .json ()["web" ]["results" ]
30- return {
31- "provider" : "brave" ,
32- "results" : [
33- {
34- "title" : x ["title" ],
35- "url" : x ["url" ],
36- "description" : x .get ("description" , "" ),
37- }
38- for x in results
39- ],
40- }
41- except httpx .HTTPStatusError as e :
42- logger .warning (
43- f"Brave Search API returned status code { e .response .status_code } "
44- )
45- except httpx .TimeoutException :
46- logger .warning ("Brave Search API request timed out" )
47- except Exception as e :
48- logger .warning (f"Error using Brave Search: { str (e )} " )
25+ import asyncio
26+
27+ attempts = 3
28+ for attempt in range (1 , attempts + 1 ):
29+ try :
30+ async with httpx .AsyncClient () as client :
31+ r = await client .get (url , headers = headers , params = params , timeout = 10 )
32+ r .raise_for_status ()
33+ results = r .json ()["web" ]["results" ]
34+ return {
35+ "provider" : "brave" ,
36+ "results" : [
37+ {
38+ "title" : x ["title" ],
39+ "url" : x ["url" ],
40+ "description" : x .get ("description" , "" ),
41+ }
42+ for x in results
43+ ],
44+ }
45+ except httpx .HTTPStatusError as e :
46+ status = e .response .status_code if e .response is not None else None
47+ if status == 429 and attempt < attempts :
48+ logger .info ("Brave rate limited (429); retrying in 1s (%d/%d)" , attempt , attempts )
49+ await asyncio .sleep (1 )
50+ continue
51+ logger .warning (
52+ f"Brave Search API returned status code { status } "
53+ )
54+ break
55+ except httpx .TimeoutException :
56+ logger .warning ("Brave Search API request timed out" )
57+ break
58+ except Exception as e :
59+ logger .warning (f"Error using Brave Search: { str (e )} " )
60+ break
4961
5062 return None
5163
0 commit comments