Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,9 @@ GROQ_API_KEY= <groq_api_key>
PINECONE_API_KEY = <your_pinecone_API_KEY>
PORT = 8000
SEARCH_KEY = <your_Google_custom_search_engine_API_key>
# Optional: use Keenable Search instead of Google Custom Search (DuckDuckGo stays the fallback)
# SEARCH_PROVIDER=keenable
# KEENABLE_API_KEY= # optional
```

*Run backend:*
Expand Down
9 changes: 9 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ PINECONE_API_KEY=your_pinecone_api_key_here
# Used for real-time fact checking via web search
SEARCH_KEY=your_google_search_api_key_here

# 3b. Optional Keenable Search (off by default)
# Set SEARCH_PROVIDER=keenable to use Keenable instead of Google Custom Search
# for claim checks. DuckDuckGo remains the fallback. An API key is optional;
# keyless calls use the public endpoint. Google's Custom Search JSON API is
# scheduled to shut down on 1 January 2027:
# https://developers.google.com/custom-search/v1/overview
# SEARCH_PROVIDER=keenable
# KEENABLE_API_KEY=

# 4. Backend Server Port (Default: 8000 for local dev, 7860 for Hugging Face Spaces)
PORT=8000

Expand Down
6 changes: 4 additions & 2 deletions backend/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ Errors: [400](#400-bad-request-unsafe-url) for an unsafe URL, [422](#422-unproce
Fetches and cleans the article, then runs the LangGraph workflow ([`app/modules/langgraph_builder.py`](app/modules/langgraph_builder.py)):

1. **Sentiment** of the article (`SENTIMENT_MODEL`).
2. **Fact checking:** extract claims (`CLAIM_EXTRACTOR_MODEL`), search the web for each (Google Custom Search when `SEARCH_KEY` is set, otherwise DuckDuckGo), and verify each claim against the top result (`FACT_VERIFIER_MODEL`). At most `MAX_CLAIMS` (3) claims are checked. If no claims can be parsed, the first sentences of the article are used.
2. **Fact checking:** extract claims (`CLAIM_EXTRACTOR_MODEL`), search the web for each (Keenable Search first when `SEARCH_PROVIDER=keenable`, otherwise Google Custom Search when `SEARCH_KEY` is set; DuckDuckGo is the fallback), and verify each claim against the top result (`FACT_VERIFIER_MODEL`). At most `MAX_CLAIMS` (3) claims are checked. If no claims can be parsed, the first sentences of the article are used.
3. **Counter-perspective** generation (`PERSPECTIVE_MODEL`).
4. **Judging** the perspective with a 0 to 100 score (`JUDGE_MODEL`). A score below `PERSPECTIVE_MIN_SCORE` (70) regenerates the perspective, up to `PERSPECTIVE_MAX_RETRIES` (3) attempts in total; the last attempt is returned even if it scores below 70.
5. **Storage:** the perspective and each fact are embedded (`EMBEDDING_MODEL`) and upserted into the Pinecone index `perspective`, namespace `default`. `/api/chat` searches this data. A storage failure is logged and does not change the response.
Expand Down Expand Up @@ -247,6 +247,8 @@ Copy [`.env.example`](.env.example) to `.env` in `backend/`. Model names, sampli
|----------|----------|----------|
| `GROQ_API_KEY` | yes | All LLM calls. The Groq clients are created at startup, so the server does not start without it. |
| `PINECONE_API_KEY` | yes | Storing and searching analyses. Checked at startup ([`app/db/vector_store.py`](app/db/vector_store.py)), which also creates the `perspective` index (384 dimensions, cosine, AWS `us-east-1` serverless) if it does not exist. |
| `SEARCH_KEY` | no | Google Custom Search key for fact checking. When unset or left as the `.env.example` placeholder, DuckDuckGo is used instead. |
| `SEARCH_KEY` | no | Google Custom Search key for fact checking. When unset or left as the `.env.example` placeholder, DuckDuckGo is used instead, unless `SEARCH_PROVIDER=keenable`. |
| `SEARCH_PROVIDER` | no | Set to `keenable` to use Keenable Search first for fact checking, with DuckDuckGo as the fallback. Unset or any other value keeps the Google Custom Search then DuckDuckGo path. |
| `KEENABLE_API_KEY` | no | Keenable Search API key, used only when `SEARCH_PROVIDER=keenable`. Optional: without it, the backend uses the keyless public endpoint. |
| `PORT` | no | Listening port; defaults to `7860`. The server binds to `0.0.0.0`. |
| `HF_TOKEN` | no | Not read by the backend code. The Hugging Face Hub library uses it, if set, when downloading the embedding model. Deploying to Hugging Face Spaces uses the `HF_TOKEN` GitHub Actions secret. |
9 changes: 9 additions & 0 deletions backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@
GOOGLE_SEARCH_TIMEOUT_SECONDS = 8
SEARCH_KEY_PLACEHOLDER = "your_google_search_api_key_here" # value from .env.example
DDG_MAX_RESULTS = 3
# Opt-in Keenable Search (SEARCH_PROVIDER=keenable). Off by default so Google
# CSE and the DuckDuckGo fallback keep their current behaviour.
# Google's Custom Search JSON API is scheduled to shut down on 1 January 2027:
# https://developers.google.com/custom-search/v1/overview
KEENABLE_PUBLIC_SEARCH_URL = "https://api.keenable.ai/v1/search/public"
KEENABLE_SEARCH_URL = "https://api.keenable.ai/v1/search"
KEENABLE_SEARCH_TIMEOUT_SECONDS = 8
KEENABLE_SEARCH_TITLE = "Perspective"
KEENABLE_SEARCH_MAX_RESULTS = 3

# --- Scraping ---------------------------------------------------------------
SCRAPER_USER_AGENT = (
Expand Down
93 changes: 90 additions & 3 deletions backend/app/modules/facts_check/web_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@
web_search.py
-------------
Provides a search wrapper for performing claim verification queries.
Attempts Google Custom Search if configured, with an automatic fallback
to DuckDuckGo search.

The default path is unchanged: Google Custom Search when a key is
configured, with an automatic fallback to DuckDuckGo.

Set SEARCH_PROVIDER=keenable to use Keenable Search instead of Google
Custom Search, still falling back to DuckDuckGo if that call fails or
returns nothing. An API key is optional (KEENABLE_API_KEY); keyless
calls go to the public endpoint and send an X-Keenable-Title header.
Google's Custom Search JSON API is scheduled to shut down on
1 January 2027 (https://developers.google.com/custom-search/v1/overview).
"""

import os
Expand All @@ -16,18 +24,97 @@
GOOGLE_SEARCH_ENGINE_ID,
GOOGLE_SEARCH_TIMEOUT_SECONDS,
GOOGLE_SEARCH_URL,
KEENABLE_PUBLIC_SEARCH_URL,
KEENABLE_SEARCH_MAX_RESULTS,
KEENABLE_SEARCH_TIMEOUT_SECONDS,
KEENABLE_SEARCH_TITLE,
KEENABLE_SEARCH_URL,
SEARCH_KEY_PLACEHOLDER,
)

logger = setup_logger(__name__)
load_dotenv()

GOOGLE_SEARCH = os.getenv("SEARCH_KEY")
# Opt-in only. Anything other than "keenable" keeps the Google-then-DDG path.
SEARCH_PROVIDER = (os.getenv("SEARCH_PROVIDER") or "google").strip().lower()
KEENABLE_API_KEY = (os.getenv("KEENABLE_API_KEY") or "").strip()


def _keenable_enabled():
return SEARCH_PROVIDER == "keenable"


def _keenable_hit(item):
"""Keep the first ranked hit that has a usable URL and evidence text."""
if not isinstance(item, dict):
return None
url = item.get("url") or item.get("link") or ""
if not isinstance(url, str) or not url.strip():
return None
snippet = item.get("snippet") or item.get("content") or item.get("description") or ""
if not isinstance(snippet, str) or not snippet.strip():
return None
raw_title = item.get("title")
title = raw_title if isinstance(raw_title, str) else ""
return {
"title": title,
"link": url,
"snippet": snippet,
}


def _first_keenable_result(payload):
if not isinstance(payload, dict):
return None
items = payload.get("results") or []
if not isinstance(items, list):
return None
for item in items:
hit = _keenable_hit(item)
if hit:
return hit
return None


def _search_keenable(query):
api_key = KEENABLE_API_KEY
url = KEENABLE_SEARCH_URL if api_key else KEENABLE_PUBLIC_SEARCH_URL
headers = {
"Content-Type": "application/json",
"X-Keenable-Title": KEENABLE_SEARCH_TITLE,
}
if api_key:
headers["X-API-Key"] = api_key
response = requests.post(
url,
json={
"query": query,
"max_results": KEENABLE_SEARCH_MAX_RESULTS,
"disable_cards": True,
},
headers=headers,
timeout=KEENABLE_SEARCH_TIMEOUT_SECONDS,
)
response.raise_for_status()
return _first_keenable_result(response.json())


def search_google(query):
# 0. Opt-in Keenable path: replace Google CSE, keep DuckDuckGo as fallback.
if _keenable_enabled():
try:
first = _search_keenable(query)
if first:
return [first]
except Exception as exc:
logger.warning(
"Keenable search error, falling back to DuckDuckGo: %s",
type(exc).__name__,
)

# 1. Try Google Custom Search if a valid key is provided
if GOOGLE_SEARCH and GOOGLE_SEARCH != SEARCH_KEY_PLACEHOLDER:
elif GOOGLE_SEARCH and GOOGLE_SEARCH != SEARCH_KEY_PLACEHOLDER:
try:
results = requests.get(
GOOGLE_SEARCH_URL,
Expand Down
167 changes: 164 additions & 3 deletions backend/tests/test_search_and_claims.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
GOOGLE_SEARCH_ENGINE_ID,
GOOGLE_SEARCH_TIMEOUT_SECONDS,
GOOGLE_SEARCH_URL,
KEENABLE_PUBLIC_SEARCH_URL,
KEENABLE_SEARCH_MAX_RESULTS,
KEENABLE_SEARCH_TIMEOUT_SECONDS,
KEENABLE_SEARCH_TITLE,
KEENABLE_SEARCH_URL,
SEARCH_KEY_PLACEHOLDER,
)
from app.modules.facts_check import llm_processing
Expand All @@ -22,25 +27,61 @@
DDG_RESULT = [{"title": "DDG bridge", "link": "https://ddg.example/bridge", "snippet": "Opened in March."}]


KEENABLE_ITEM = {
"title": "Keenable bridge",
"url": "https://keenable.example/bridge",
"snippet": "It cost 40M according to Keenable.",
}
KEENABLE_RESULT = [
{
"title": "Keenable bridge",
"link": "https://keenable.example/bridge",
"snippet": "It cost 40M according to Keenable.",
}
]


@pytest.fixture
def search(monkeypatch):
"""Fake both search providers; `config` sets their replies and `calls` records the requests."""
calls = {"google": [], "ddg": []}
config = {"google": {"items": [GOOGLE_ITEM]}, "ddg": [DDG_ITEM]}
calls = {"google": [], "ddg": [], "keenable": []}
config = {
"google": {"items": [GOOGLE_ITEM]},
"ddg": [DDG_ITEM],
"keenable": {"results": [KEENABLE_ITEM]},
}

class FakeResponse:
def __init__(self, payload):
def __init__(self, payload, status=200):
self.payload = payload
self.status_code = status

def json(self):
return self.payload

def raise_for_status(self):
if isinstance(self.payload, Exception):
raise self.payload
if self.status_code >= 400:
raise RuntimeError(f"status {self.status_code}")

def fake_get(url, params, timeout):
calls["google"].append({"url": url, "params": params, "timeout": timeout})
if isinstance(config["google"], Exception):
raise config["google"]
return FakeResponse(config["google"])

def fake_post(url, json=None, headers=None, timeout=None):
calls["keenable"].append(
{"url": url, "json": json, "headers": headers, "timeout": timeout}
)
if isinstance(config["keenable"], Exception):
raise config["keenable"]
if isinstance(config["keenable"], tuple):
payload, status = config["keenable"]
return FakeResponse(payload, status=status)
return FakeResponse(config["keenable"])

class FakeDDGS:
def text(self, query, max_results):
calls["ddg"].append({"query": query, "max_results": max_results})
Expand All @@ -49,8 +90,11 @@ def text(self, query, max_results):
return iter(config["ddg"])

monkeypatch.setattr(web_search.requests, "get", fake_get)
monkeypatch.setattr(web_search.requests, "post", fake_post)
monkeypatch.setattr(web_search, "DDGS", FakeDDGS)
monkeypatch.setattr(web_search, "GOOGLE_SEARCH", "configured-google-key")
monkeypatch.setattr(web_search, "SEARCH_PROVIDER", "google")
monkeypatch.setattr(web_search, "KEENABLE_API_KEY", "")
return config, calls


Expand Down Expand Up @@ -111,9 +155,126 @@ def test_returns_nothing_when_both_providers_come_up_empty(search, ddg_reply):
assert web_search.search_google(QUERY) == []



def test_google_is_still_used_when_keenable_is_not_selected(search):
_, calls = search

assert web_search.search_google(QUERY) == [
{"title": "Bridge budget", "link": "https://news.example/budget", "snippet": "It cost 40M."}
]
assert calls["keenable"] == []
assert calls["ddg"] == []


def test_keenable_is_used_when_search_provider_is_keenable(search, monkeypatch):
_, calls = search
monkeypatch.setattr(web_search, "SEARCH_PROVIDER", "keenable")

assert web_search.search_google(QUERY) == KEENABLE_RESULT
assert calls["keenable"] == [
{
"url": KEENABLE_PUBLIC_SEARCH_URL,
"json": {
"query": QUERY,
"max_results": KEENABLE_SEARCH_MAX_RESULTS,
"disable_cards": True,
},
"headers": {
"Content-Type": "application/json",
"X-Keenable-Title": KEENABLE_SEARCH_TITLE,
},
"timeout": KEENABLE_SEARCH_TIMEOUT_SECONDS,
}
]
assert calls["google"] == []
assert calls["ddg"] == []


def test_keenable_sends_api_key_on_the_keyed_endpoint(search, monkeypatch):
_, calls = search
monkeypatch.setattr(web_search, "SEARCH_PROVIDER", "keenable")
monkeypatch.setattr(web_search, "KEENABLE_API_KEY", "test-keenable-key")

assert web_search.search_google(QUERY) == KEENABLE_RESULT
assert calls["keenable"][0]["url"] == KEENABLE_SEARCH_URL
assert calls["keenable"][0]["headers"]["X-API-Key"] == "test-keenable-key"
assert calls["keenable"][0]["headers"]["X-Keenable-Title"] == KEENABLE_SEARCH_TITLE
assert calls["google"] == []


@pytest.mark.parametrize(
"keenable_reply",
[
{"results": []},
({"results": [KEENABLE_ITEM]}, 502),
RuntimeError("timeout"),
],
ids=["no-results", "api-error", "request-fails"],
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)
def test_duckduckgo_is_used_when_keenable_finds_nothing_or_fails(search, monkeypatch, keenable_reply):
config, calls = search
monkeypatch.setattr(web_search, "SEARCH_PROVIDER", "keenable")
config["keenable"] = keenable_reply

assert web_search.search_google(QUERY) == DDG_RESULT
assert len(calls["keenable"]) == 1
assert len(calls["ddg"]) == 1
assert calls["google"] == []


def test_keenable_coerces_non_string_titles(search, monkeypatch):
config, calls = search
monkeypatch.setattr(web_search, "SEARCH_PROVIDER", "keenable")
config["keenable"] = {
"results": [
{"title": None, "url": "https://keenable.example/none"},
{"title": 42, "url": "https://keenable.example/num", "snippet": "Numeric title."},
]
}

assert web_search.search_google(QUERY) == [
{
"title": "",
"link": "https://keenable.example/num",
"snippet": "Numeric title.",
}
]
assert calls["ddg"] == []


def test_keenable_skips_hits_without_evidence_and_falls_back(search, monkeypatch):
config, calls = search
monkeypatch.setattr(web_search, "SEARCH_PROVIDER", "keenable")
config["keenable"] = {
"results": [
{"title": "Title only", "url": "https://keenable.example/empty", "snippet": " "},
{"title": "No URL", "snippet": "Has text but no link"},
KEENABLE_ITEM,
]
}

assert web_search.search_google(QUERY) == KEENABLE_RESULT
assert calls["ddg"] == []


def test_keenable_falls_back_when_no_hit_has_evidence(search, monkeypatch):
config, calls = search
monkeypatch.setattr(web_search, "SEARCH_PROVIDER", "keenable")
config["keenable"] = {
"results": [
{"title": "Title only", "url": "https://keenable.example/empty"},
{"title": "Blank snippet", "url": "https://keenable.example/blank", "snippet": ""},
]
}

assert web_search.search_google(QUERY) == DDG_RESULT
assert len(calls["ddg"]) == 1


# --- claim extractor ---------------------------------------------------------------------



def test_claim_extractor_returns_the_model_output_with_the_state(monkeypatch, fake_chat_client):
client = fake_chat_client(" 1. The bridge cost 40M.\n2. It opened in March. \n")
monkeypatch.setattr(llm_processing, "client", client)
Expand Down