Skip to content

Commit e99b704

Browse files
committed
Release v0.8.10: combined web search, Lynx browsing and citation formatting
1 parent 6513d32 commit e99b704

14 files changed

Lines changed: 676 additions & 212 deletions

‎README.md‎

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

288288
> The current application version is stored in the repository-root `VERSION` file and loaded by the runtime from there. Update `VERSION` once for a release instead of duplicating the current version in source files.
289289
290+
- v0.8.10 - Preserve formatting in replies with web citations
291+
- Render the formatted reply before adding source links, so bold and italics display correctly after web tool calls.
292+
- Split long cited replies with balanced HTML tags, keeping code literal and citation links intact.
293+
294+
- v0.8.9 - Fetch DuckDuckGo and webpages directly with Lynx
295+
- DuckDuckGo uses `lynx -dump` to fetch the results page. Its dump joins OpenAI and enabled Perplexity results in the combined search response.
296+
- The separate `get_website_dump` tool also fetches URLs directly with Lynx. Timeouts cancel and reap the Lynx process.
297+
298+
- v0.8.8 - Restore Lynx browsing after web search
299+
- The primary model can call `get_website_dump` after receiving combined search results and use the retrieved page content in its final answer.
300+
- Follow-up web calls preserve local context and distinct clickable citations. `[WebSearch] MaxWebToolCalls` defaults to four calls per reply.
301+
290302
- v0.8.7 - Combined web search and news retrieval fallback
291303
- Each web search sends the tool query to all enabled providers under one timeout and returns their findings and citations in one tool result. DuckDuckGo and OpenAI are enabled by default.
292304
- Elasticsearch news actions retain their existing tokens. Failed or stale RSS feeds can use publisher-scoped web search and the corresponding section page. See [web search settings](docs/WEB_SEARCH.md).

‎VERSION‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
0.8.7
1+
0.8.10

‎docs/WEB_SEARCH.md‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Web search and news retrieval
22

3-
The primary Chat Completions model can call `search_web({"query": "..."})`. The Python handler selects providers from `config/config.ini`. Each receives the query supplied in that call. The handler returns provider-labelled evidence in one tool result. Only the primary model receives the chat history when writing the Telegram reply. OpenAI's hosted search uses the existing project key and a separate request to `POST /v1/responses`. Each invocation requests one hosted web search.
3+
The primary Chat Completions model can call `search_web({"query": "..."})`. The Python handler selects providers from `config/config.ini`. Each receives the query supplied in that call. The handler returns provider-labelled evidence in one tool result. The primary model can then call `get_website_dump` to read selected URLs through Lynx before answering. Each webpage result is returned in its own tool message alongside the existing local context and search evidence. Only the primary model receives the chat history when writing the Telegram reply. OpenAI's hosted search uses the existing project key and a separate request to `POST /v1/responses`. Each invocation requests one hosted web search.
44

55
## Install the ZIP update on Linux
66

@@ -25,6 +25,7 @@ UseOpenAIWebSearch = True
2525
OpenAIModel = gpt-6-luna
2626
FallbackToOpenAI = True
2727
TimeoutSeconds = 30
28+
MaxWebToolCalls = 4
2829
NewsMaxAgeDays = 7
2930

3031
[DuckDuckGo]
@@ -34,7 +35,7 @@ Enabled = True
3435
Enabled = True
3536
```
3637

37-
Perplexity also needs the existing `PERPLEXITY_API_KEY` environment variable. DuckDuckGo uses the existing Lynx installation. Every model-requested web search starts all enabled providers concurrently and gives the primary model their results together, with provider labels and source links. DuckDuckGo and initial OpenAI web search default to enabled. Perplexity retains its existing enabled setting. Earlier `DefaultProvider` entries are ignored. Only the standalone diagnostic command can select an individual provider.
38+
Perplexity also needs the existing `PERPLEXITY_API_KEY` environment variable. DuckDuckGo runs `lynx -dump -width=200` against the search URL directly. The separate `get_website_dump` tool uses the same direct Lynx fetch. Every model-requested web search starts all enabled providers concurrently and gives the primary model their results together, with provider labels and source links. DuckDuckGo and initial OpenAI web search default to enabled. Perplexity retains its existing enabled setting. Earlier `DefaultProvider` entries are ignored. Only the standalone diagnostic command can select an individual provider.
3839

3940
| UseOpenAIWebSearch | FallbackToOpenAI | OpenAI hosted search behavior with the master switch enabled |
4041
| --- | --- | --- |
@@ -45,8 +46,16 @@ Perplexity also needs the existing `PERPLEXITY_API_KEY` environment variable. Du
4546

4647
`OpenAIEnabled = False` disables hosted OpenAI search on every path. The primary Chat Completions model continues answering as usual. To change a setting, edit the existing `[WebSearch]` section and restart the bot.
4748

49+
`MaxWebToolCalls` counts the initial search or page call and any follow-up web tool calls made by the primary model, up to four by default. Each search still combines all enabled providers under one shared deadline. The model can read several pages and keeps the source URLs from earlier results. Failed page reads return an explicit failure to the model so it can use the remaining evidence. Direct Lynx browsing uses `get_website_dump` independently of the optional `[DuckDuckGo] EnableAgenticBrowsing` setting.
50+
4851
A multi-search starts the selected providers concurrently. One wall-clock deadline covers HTTP requests, retries and DuckDuckGo's optional browsing step. At the deadline the handler cancels unfinished local tasks and returns completed results. A failed lookup can use OpenAI at most once. A blocked website dump respects the existing domain restriction policy.
4952

53+
## Telegram reply formatting
54+
55+
Replies following web tool calls use the normal Markdown-to-HTML conversion before citation links are added. The model is instructed to use Telegram HTML and retain citation markers such as `[D1]`, `[O11]` and `[W2]`. Bold, italics and code are rendered by the bot even when the model uses Markdown. Citation replacement operates on text outside code and existing links. Long replies close and reopen formatting tags at message boundaries; source URLs and HTML entities are not cut in half. Source titles are escaped as text if the reply omits citation markers.
56+
57+
Version 0.8.10 fixes a branch that discarded the converted reply whenever web sources were present, leaving Markdown emphasis visible while citation links worked. This is a rendering correction; provider selection, direct Lynx fetching, tool availability and search deadlines retain their v0.8.9 behavior.
58+
5059
## Elasticsearch news actions
5160

5261
All 85 publisher/category action names continue to match existing Elasticsearch entries. A trigger first tries its configured RSS endpoint. A missing feed, HTTP error, unexpected content type, empty feed, or absence of recent usable articles immediately starts a publisher-scoped search when `FallbackToOpenAI` and `OpenAIEnabled` are enabled. OpenAI runs alongside enabled DuckDuckGo and Perplexity providers. Results are filtered to the specified publisher and dates. The search is limited to the publisher's domains and requests the trigger's particular section, language or region. It requires dated article citations. If that search is disabled, unavailable or yields no usable items, the action tries the corresponding publisher section page. If all routes fail, the primary model receives an explicit retrieval failure.
@@ -83,4 +92,4 @@ With three configured, reachable providers, the combined check prints three labe
8392

8493
The OpenAI API contract and supported models are documented in the [web search guide](https://developers.openai.com/api/docs/guides/tools-web-search), [Responses reference](https://developers.openai.com/api/reference/resources/responses/methods/create) and [GPT-6 Luna model page](https://developers.openai.com/api/docs/models/gpt-6-luna).
8594

86-
In this workspace the DuckDuckGo HTML endpoint served a challenge page. The adapter reports that as a failed search, even if the challenge contains feedback or navigation links. Publisher retrieval was tested live. OpenAI and Perplexity responses were tested with fixtures and HTTP mocks. No provider credentials or Telegram token were included in the snapshot.
95+
The earlier HTTPX-based DuckDuckGo fetch served challenge pages. The deployment-host test supplied for v0.8.9 returned search results with direct Lynx. The adapter rejects dumps containing no external result links. Regression tests use a representative Lynx dump and mocked subprocess and provider responses. Publisher retrieval was tested live. OpenAI and Perplexity responses were tested with fixtures and HTTP mocks. No provider credentials or Telegram token were included in the snapshot.

‎src/api_get_duckduckgo_search.py‎

Lines changed: 27 additions & 137 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
DuckDuckGo search helper module for ChatKeke.
88
99
Purpose:
10-
- Fetch web content over HTTPS with httpx and render it through lynx locally.
11-
- Fetch DuckDuckGo HTML search results without relying on Lynx/GnuTLS networking.
10+
- Fetch DuckDuckGo results and webpages directly with Lynx.
11+
- Return the Lynx dump as search evidence with decoded source URLs.
1212
- Optionally run a small OpenAI sub-agent over those results.
1313
- Optionally let the sub-agent request one webpage dump via a local
1414
visit_webpage tool.
@@ -32,15 +32,13 @@
3232
import random
3333
import re
3434
import sys
35-
import traceback
3635
from typing import Any, Dict, List, Optional
37-
from urllib.parse import quote, unquote_plus
36+
from urllib.parse import quote, unquote_plus, urlsplit
3837

3938
import httpx
4039
from config_paths import CONFIG_PATH
4140
from api_key import APIKeyConfigurationError, build_openai_headers
4241
from openai_reasoning_compat import apply_reasoning_effort
43-
from app_version import VERSION as CHATKEKE_VERSION
4442

4543

4644
# ---------------------------------------------------------------------------
@@ -67,10 +65,7 @@
6765
DEFAULT_DDG_MAX_CONTENT_SIZE = 10000
6866

6967
OPENAI_CHAT_COMPLETIONS_ENDPOINT = "https://api.openai.com/v1/chat/completions"
70-
# Use DuckDuckGo's canonical HTML host directly. Older Lynx/GnuTLS builds can
71-
# successfully connect to both hosts separately yet fail the second TLS handshake
72-
# when duckduckgo.com redirects to html.duckduckgo.com. Going direct avoids that
73-
# unnecessary redirect while keeping the same HTML search endpoint.
68+
# Use the same canonical HTML URL as a direct Lynx search.
7469
DUCKDUCKGO_HTML_ENDPOINT = "https://html.duckduckgo.com/html/"
7570

7671

@@ -349,143 +344,33 @@ def _dedupe_lines_with_links(text: str) -> str:
349344

350345

351346
async def _run_lynx_dump(url: str, request_timeout=None) -> str:
352-
"""
353-
Fetch a URL with httpx, then render the returned HTML through Lynx locally.
354-
355-
Lynx is intentionally not allowed to perform the HTTPS request itself. Some
356-
older Lynx/GnuTLS builds intermittently fail TLS handshakes when Keke runs as
357-
a service even though the same URL works from an interactive shell. httpx is
358-
already used by Keke and provides the network transport; Lynx only converts
359-
the downloaded HTML into the existing text-dump format.
360-
361-
Raises RuntimeError on HTTP or Lynx rendering failure.
362-
"""
363-
headers = {
364-
"User-Agent": f"Lynx/2.9.0 ChatKeke/{CHATKEKE_VERSION}",
365-
"Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8",
366-
}
367-
368-
# Passing a custom transport disables HTTPX's environment proxy routing.
369-
# Retry only connection setup failures, as the previous transport did.
370-
try:
371-
async with httpx.AsyncClient(
372-
follow_redirects=True, timeout=request_timeout or max(1, timeout), headers=headers
373-
) as client:
374-
for attempt in range(3):
375-
try:
376-
response = await client.get(url)
377-
break
378-
except (httpx.ConnectError, httpx.ConnectTimeout):
379-
if attempt == 2:
380-
raise
381-
await asyncio.sleep(0.5 * attempt)
382-
response.raise_for_status()
383-
if url.startswith(DUCKDUCKGO_HTML_ENDPOINT + "?"):
384-
from bs4 import BeautifulSoup
385-
if not BeautifulSoup(response.content, "lxml").select_one("a.result__a[href]"):
386-
raise RuntimeError("DuckDuckGo returned no search result links")
387-
except httpx.HTTPStatusError as exc:
388-
response = exc.response
389-
body_preview = response.text[:2000] if response is not None else "<no response body>"
390-
391-
# Log with a traceback AND print directly to stderr so failures are visible
392-
# even when a service/logger configuration changes.
393-
logger.exception(
394-
"HTTP status failure while fetching %s: status=%s reason=%r body=%r",
395-
url,
396-
getattr(response, "status_code", None),
397-
getattr(response, "reason_phrase", None),
398-
body_preview,
399-
)
400-
print(
401-
"\n========== DUCKDUCKGO HTTP STATUS ERROR ==========\n"
402-
f"URL: {url}\n"
403-
f"TYPE: {type(exc).__name__}\n"
404-
f"REPR: {exc!r}\n"
405-
f"STATUS: {getattr(response, 'status_code', None)}\n"
406-
f"REASON: {getattr(response, 'reason_phrase', None)!r}\n"
407-
f"BODY: {body_preview!r}\n"
408-
"TRACEBACK:",
409-
file=sys.stderr,
410-
flush=True,
411-
)
412-
traceback.print_exc(file=sys.stderr)
413-
print(
414-
"==================================================\n",
415-
file=sys.stderr,
416-
flush=True,
417-
)
418-
raise RuntimeError(
419-
f"HTTP status fetch failed for {url}: "
420-
f"{type(exc).__name__}: {exc!r}"
421-
) from exc
422-
423-
except httpx.RequestError as exc:
424-
request_url = str(exc.request.url) if getattr(exc, "request", None) else url
425-
cause = exc.__cause__
426-
427-
logger.exception(
428-
"HTTP transport failure while fetching %s: type=%s repr=%r cause=%r",
429-
request_url,
430-
type(exc).__name__,
431-
exc,
432-
cause,
433-
)
434-
print(
435-
"\n========== DUCKDUCKGO HTTP TRANSPORT ERROR ==========\n"
436-
f"URL: {request_url}\n"
437-
f"TYPE: {type(exc).__name__}\n"
438-
f"REPR: {exc!r}\n"
439-
f"STR: {exc!s}\n"
440-
f"CAUSE: {cause!r}\n"
441-
"TRACEBACK:",
442-
file=sys.stderr,
443-
flush=True,
444-
)
445-
traceback.print_exc(file=sys.stderr)
446-
print(
447-
"=====================================================\n",
448-
file=sys.stderr,
449-
flush=True,
450-
)
451-
raise RuntimeError(
452-
f"HTTP transport fetch failed for {request_url}: "
453-
f"{type(exc).__name__}: {exc!r}; cause={cause!r}"
454-
) from exc
455-
456-
# Preserve correct resolution of relative links when Lynx parses HTML from
457-
# stdin rather than fetching the original URL itself. A document-level BASE
458-
# element is sufficient for Lynx to emit absolute references in --dump.
459-
final_url = str(response.url)
460-
base_tag = f'<base href="{final_url}">\n'.encode("utf-8")
461-
html_bytes = base_tag + response.content
462-
347+
"""Have Lynx fetch and render the URL directly, with cancellable process cleanup."""
348+
if not isinstance(url, str) or urlsplit(url).scheme not in ("http", "https"):
349+
raise RuntimeError("Lynx browsing requires an HTTP or HTTPS URL")
350+
logger.info("Fetching URL directly with Lynx: %s", url)
463351
process = await asyncio.create_subprocess_exec(
464-
"lynx",
465-
"-dump",
466-
"-force_html",
467-
"-stdin",
468-
stdin=asyncio.subprocess.PIPE,
352+
"lynx", "-dump", "-width=200", "-display_charset=UTF-8", url,
353+
stdin=asyncio.subprocess.DEVNULL,
469354
stdout=asyncio.subprocess.PIPE,
470355
stderr=asyncio.subprocess.PIPE,
471356
)
472-
473357
try:
474-
stdout, stderr = await process.communicate(input=html_bytes)
475-
except asyncio.CancelledError:
358+
stdout, stderr = await asyncio.wait_for(
359+
process.communicate(), timeout=request_timeout or max(1, timeout))
360+
finally:
476361
if process.returncode is None:
477362
try:
478363
process.kill()
479364
except ProcessLookupError:
480365
pass
481-
await process.wait()
482-
raise
483-
366+
await process.wait()
484367
if process.returncode != 0:
485-
error_message = stderr.decode("utf-8", errors="replace").strip()
486-
raise RuntimeError(error_message or f"lynx exited with code {process.returncode}")
487-
488-
return stdout.decode("utf-8", errors="replace")
368+
detail = stderr.decode("utf-8", errors="replace").strip()
369+
raise RuntimeError(detail or f"Lynx exited with code {process.returncode}")
370+
content = stdout.decode("utf-8", errors="replace").strip()
371+
if not content:
372+
raise RuntimeError("Lynx returned an empty page")
373+
return content
489374

490375

491376
def _build_duckduckgo_search_url(search_terms: str) -> str:
@@ -502,6 +387,11 @@ async def _fetch_duckduckgo_results(search_terms: str, request_timeout=None) ->
502387
response_text = await _run_lynx_dump(search_url, request_timeout)
503388
cleaned_text = parse_duckduckgo(response_text)
504389
unique_text = _dedupe_lines_with_links(cleaned_text)
390+
urls = re.findall(r"https?://[^\s<>]+", unique_text)
391+
result_hosts = [urlsplit(url).hostname or "" for url in urls]
392+
if not any(host and host not in ("duckduckgo.com", "duck.co")
393+
and not host.endswith((".duckduckgo.com", ".duck.co")) for host in result_hosts):
394+
raise RuntimeError("DuckDuckGo returned no result links in its Lynx dump")
505395

506396
logger.info(unique_text)
507397

@@ -520,10 +410,10 @@ async def get_duckduckgo_search(search_terms, user_message, openai_auth=None, re
520410
It does not send messages to Telegram directly.
521411
"""
522412
try:
523-
search_terms = (search_terms or "").strip()
413+
search_terms = search_terms or ""
524414
user_message = user_message or ""
525415

526-
if not search_terms:
416+
if not search_terms.strip():
527417
logger.warning("get_duckduckgo_search called with empty search_terms.")
528418
return "Error: empty DuckDuckGo search query."
529419

‎src/api_get_website_dump.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ async def get_website_dump(url, max_tokens=10000):
6161
return error_message
6262

6363
try:
64-
# Check HTTP status before rendering; Lynx can otherwise dump a 404 as text.
64+
# Lynx performs the network request and produces the page dump.
6565
content = await asyncio.wait_for(_run_lynx_dump(url, request_timeout=15), timeout=15)
6666
content = re.sub(r'[^\S\n]+', ' ', content).strip()
6767
content = re.sub(r'\n{3,}', '\n\n', content)

‎src/custom_functions.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ async def observe_chat():
6868

6969
custom_functions.append({
7070
"name": "search_web",
71-
"description": "Search the web when current information or external verification is needed.",
71+
"description": "Find sources using all enabled search providers. Use get_website_dump to read a result page when its contents are needed.",
7272
"parameters": {
7373
"type": "object",
7474
"properties": {"query": {"type": "string", "description": "The search query only."}},
@@ -80,7 +80,7 @@ async def observe_chat():
8080
# website fetcher and dumper
8181
custom_functions.append({
8282
'name': 'get_website_dump',
83-
'description': '[Use to fetch information from a specific website.] Fetches the content of a website using the lynx --dump command and returns the plain text output.',
83+
'description': 'Browse a specific URL with Lynx and return its plain text page content. Use for URLs the user asks you to read or summarize, and to open relevant search results when their full content is needed.',
8484
'parameters': {
8585
'type': 'object',
8686
'properties': {

0 commit comments

Comments
 (0)