Skip to content

Commit dc408c8

Browse files
committed
Fix intermittent DuckDuckGo connection failures
1 parent 0bb5f17 commit dc408c8

3 files changed

Lines changed: 99 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,14 @@ If you run into any issues, consult the logs or reach out on the repository's [I
241241

242242
# Changelog
243243

244+
- v0.8.4 - DuckDuckGo search reliability hotfix
245+
- Added HTTPX connection retries for DuckDuckGo/web fetches: `httpx.AsyncHTTPTransport(retries=2)` provides up to three connection attempts before a request fails.
246+
- Fixes intermittent `httpx.ConnectError` failures observed in live service operation, including failures whose underlying cause surfaced as `BrokenResourceError`.
247+
- Added explicit console-visible diagnostics for DuckDuckGo HTTP transport and HTTP status failures, including exception type, representation, cause/status details, and traceback output.
248+
- Improved outer DuckDuckGo error logging so failed searches retain exception type and traceback instead of collapsing into an uninformative empty error string.
249+
- Retains the v0.8.3 transport architecture: HTTPX performs HTTPS fetching and Lynx renders the already-downloaded HTML locally; Lynx is not used for the DuckDuckGo network connection itself.
250+
- Verified against the live DuckDuckGo search path after the retry fix.
251+
244252
- v0.8.3 - GPT-5.6 Luna, backwards-compatible reasoning effort, and compatibility fixes
245253
- Added optional `ReasoningEffort` in `[DEFAULT]` for OpenAI Chat Completions models.
246254
- `ReasoningEffort = default` normally preserves existing behaviour by omitting the field and using the selected model's API default.

‎src/api_get_duckduckgo_search.py‎

Lines changed: 90 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
import logging
3232
import random
3333
import re
34+
import sys
35+
import traceback
3436
from typing import Any, Dict, List, Optional
3537
from urllib.parse import quote, unquote_plus
3638

@@ -359,20 +361,93 @@ async def _run_lynx_dump(url: str) -> str:
359361
Raises RuntimeError on HTTP or Lynx rendering failure.
360362
"""
361363
headers = {
362-
"User-Agent": "Lynx/2.9.0 ChatKeke/0.8.3",
364+
"User-Agent": "Lynx/2.9.0 ChatKeke/0.8.4",
363365
"Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",
364366
}
365367

368+
# HTTPX's low-level transport can retry connection-establishment failures.
369+
# The observed intermittent DDG failure is httpx.ConnectError with an
370+
# anyio.BrokenResourceError cause, so use two retries (three attempts total)
371+
# before surfacing the full diagnostic below.
372+
transport = httpx.AsyncHTTPTransport(retries=2)
373+
366374
try:
367375
async with httpx.AsyncClient(
376+
transport=transport,
368377
follow_redirects=True,
369378
timeout=max(1, timeout),
370379
headers=headers,
371380
) as client:
372381
response = await client.get(url)
373382
response.raise_for_status()
374-
except httpx.HTTPError as exc:
375-
raise RuntimeError(f"HTTP fetch failed for {url}: {exc}") from exc
383+
except httpx.HTTPStatusError as exc:
384+
response = exc.response
385+
body_preview = response.text[:2000] if response is not None else "<no response body>"
386+
387+
# Log with a traceback AND print directly to stderr so failures are visible
388+
# even when a service/logger configuration changes.
389+
logger.exception(
390+
"HTTP status failure while fetching %s: status=%s reason=%r body=%r",
391+
url,
392+
getattr(response, "status_code", None),
393+
getattr(response, "reason_phrase", None),
394+
body_preview,
395+
)
396+
print(
397+
"\n========== DUCKDUCKGO HTTP STATUS ERROR ==========\n"
398+
f"URL: {url}\n"
399+
f"TYPE: {type(exc).__name__}\n"
400+
f"REPR: {exc!r}\n"
401+
f"STATUS: {getattr(response, 'status_code', None)}\n"
402+
f"REASON: {getattr(response, 'reason_phrase', None)!r}\n"
403+
f"BODY: {body_preview!r}\n"
404+
"TRACEBACK:",
405+
file=sys.stderr,
406+
flush=True,
407+
)
408+
traceback.print_exc(file=sys.stderr)
409+
print(
410+
"==================================================\n",
411+
file=sys.stderr,
412+
flush=True,
413+
)
414+
raise RuntimeError(
415+
f"HTTP status fetch failed for {url}: "
416+
f"{type(exc).__name__}: {exc!r}"
417+
) from exc
418+
419+
except httpx.RequestError as exc:
420+
request_url = str(exc.request.url) if getattr(exc, "request", None) else url
421+
cause = exc.__cause__
422+
423+
logger.exception(
424+
"HTTP transport failure while fetching %s: type=%s repr=%r cause=%r",
425+
request_url,
426+
type(exc).__name__,
427+
exc,
428+
cause,
429+
)
430+
print(
431+
"\n========== DUCKDUCKGO HTTP TRANSPORT ERROR ==========\n"
432+
f"URL: {request_url}\n"
433+
f"TYPE: {type(exc).__name__}\n"
434+
f"REPR: {exc!r}\n"
435+
f"STR: {exc!s}\n"
436+
f"CAUSE: {cause!r}\n"
437+
"TRACEBACK:",
438+
file=sys.stderr,
439+
flush=True,
440+
)
441+
traceback.print_exc(file=sys.stderr)
442+
print(
443+
"=====================================================\n",
444+
file=sys.stderr,
445+
flush=True,
446+
)
447+
raise RuntimeError(
448+
f"HTTP transport fetch failed for {request_url}: "
449+
f"{type(exc).__name__}: {exc!r}; cause={cause!r}"
450+
) from exc
376451

377452
# Preserve correct resolution of relative links when Lynx parses HTML from
378453
# stdin rather than fetching the original URL itself. A document-level BASE
@@ -448,7 +523,12 @@ async def get_duckduckgo_search(search_terms, user_message):
448523
try:
449524
return await _fetch_duckduckgo_results(search_terms)
450525
except Exception as exc:
451-
logger.error("DuckDuckGo/lynx search failed: %s", exc)
526+
logger.exception("DuckDuckGo search failed: type=%s repr=%r", type(exc).__name__, exc)
527+
print(
528+
f"DUCKDUCKGO SEARCH FAILED: {type(exc).__name__}: {exc!r}",
529+
file=sys.stderr,
530+
flush=True,
531+
)
452532
return f"Error: {str(exc)}"
453533

454534
# Agentic path.
@@ -460,7 +540,12 @@ async def get_duckduckgo_search(search_terms, user_message):
460540
try:
461541
unique_text = await _fetch_duckduckgo_results(search_terms)
462542
except Exception as exc:
463-
logger.error("DuckDuckGo/lynx search failed: %s", exc)
543+
logger.exception("DuckDuckGo search failed: type=%s repr=%r", type(exc).__name__, exc)
544+
print(
545+
f"DUCKDUCKGO SEARCH FAILED: {type(exc).__name__}: {exc!r}",
546+
file=sys.stderr,
547+
flush=True,
548+
)
464549
return f"Error: {str(exc)}"
465550

466551
print_horizontal_line()

‎src/main.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
# https://github.com/FlyingFathead/TelegramBot-OpenAI-API
77
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
88
# version of this program
9-
version_number = "0.8.3"
9+
version_number = "0.8.4"
1010

1111
# Add the project root directory to Python's path
1212
import sys

0 commit comments

Comments
 (0)