Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

refactor(query): consolidate _infer_query_intent into lib/query.py (#436)

Ilia Alshanetsky6a07685c3e47
diff --git a/skills/last30days/scripts/lib/instagram.py b/skills/last30days/scripts/lib/instagram.py
index 5a77f9a9..b3372446 100644
--- a/skills/last30days/scripts/lib/instagram.py
+++ b/skills/last30days/scripts/lib/instagram.py
@@ -14,6 +14,7 @@ from datetime import datetime
from typing import Any, Dict, List, Optional, Set
from . import dates, http, log
+from .query import infer_query_intent
from .relevance import token_overlap_relevance as _compute_relevance
SCRAPECREATORS_BASE = "https://api.scrapecreators.com"
@@ -92,20 +93,6 @@ def _to_hashtag_form(query: str) -> str:
return ''.join(query.split()).lower()
-def _infer_query_intent(topic: str) -> str:
- """Tiny local intent classifier for Instagram query expansion."""
- text = topic.lower().strip()
- if re.search(r"\b(vs|versus|compare|difference between)\b", text):
- return "comparison"
- if re.search(r"\b(how to|tutorial|guide|setup|step by step|deploy|install)\b", text):
- return "how_to"
- if re.search(r"\b(thoughts on|worth it|should i|opinion|review)\b", text):
- return "opinion"
- if re.search(r"\b(pricing|feature|features|best .* for)\b", text):
- return "product"
- return "breaking_news"
-
-
def expand_instagram_queries(topic: str, depth: str) -> List[str]:
"""Generate multiple Instagram search queries from a topic.
@@ -125,7 +112,7 @@ def expand_instagram_queries(topic: str, depth: str) -> List[str]:
if core.lower() != original_clean.lower() and len(original_clean.split()) <= 8:
queries.append(original_clean)
- qtype = _infer_query_intent(topic)
+ qtype = infer_query_intent(topic)
# Intent-specific Instagram content-type variants
if qtype == "breaking_news":
diff --git a/skills/last30days/scripts/lib/polymarket.py b/skills/last30days/scripts/lib/polymarket.py
index 8656decd..aef7eea3 100644
--- a/skills/last30days/scripts/lib/polymarket.py
+++ b/skills/last30days/scripts/lib/polymarket.py
@@ -300,7 +300,14 @@ def _extract_domain_queries(topic: str, events: List[Dict]) -> List[str]:
def _infer_query_intent(topic: str) -> str:
- """Tiny local fallback for Polymarket search tuning only."""
+ """Narrower local classifier for Polymarket search tuning only.
+
+ Deliberately does NOT delegate to ``query.infer_query_intent``:
+ Polymarket only needs the prediction/non-prediction split, and the
+ broader classifier would route queries to ``how_to``, ``opinion``,
+ ``product``, etc. without any matching expansion branch downstream.
+ Keep this narrow until polymarket grows additional intents.
+ """
text = topic.lower().strip()
if re.search(r"\b(predict|prediction|odds|forecast|chance|probability|will .* win)\b", text):
return "prediction"
diff --git a/skills/last30days/scripts/lib/query.py b/skills/last30days/scripts/lib/query.py
index b46edbcc..38c76a10 100644
--- a/skills/last30days/scripts/lib/query.py
+++ b/skills/last30days/scripts/lib/query.py
@@ -105,6 +105,40 @@ def extract_core_subject(
return result.rstrip('?!.') if not max_words else (result or topic.lower().strip())
+def infer_query_intent(topic: str) -> str:
+ """Classify a topic into a coarse intent for adapter query expansion.
+
+ Returns one of: ``comparison``, ``how_to``, ``opinion``, ``product``,
+ ``prediction``, ``breaking_news`` (default).
+
+ The ``how_to`` regex covers both prefixed forms (``how to install``)
+ and bare imperatives (``configure``, ``troubleshoot``, ``debug``,
+ ``fix``). Adapters that previously kept their own copy of this
+ classifier had drifted to subtly different word lists; this is the
+ superset.
+
+ Polymarket keeps a custom narrower classifier (prediction-only) and
+ does NOT delegate here; its expansion only needs that signal.
+ """
+ text = topic.lower().strip()
+ if re.search(r"\b(vs|versus|compare|difference between)\b", text):
+ return "comparison"
+ if re.search(
+ r"\b(how to|tutorial|guide|setup|step by step|deploy|install|"
+ r"configuration|configure|troubleshoot|troubleshooting|error|errors|"
+ r"fix|debug)\b",
+ text,
+ ):
+ return "how_to"
+ if re.search(r"\b(thoughts on|worth it|should i|opinion|review)\b", text):
+ return "opinion"
+ if re.search(r"\b(pricing|feature|features|best .* for)\b", text):
+ return "product"
+ if re.search(r"\b(predict|prediction|odds|forecast|chance)\b", text):
+ return "prediction"
+ return "breaking_news"
+
+
def extract_compound_terms(topic: str) -> List[str]:
"""Detect multi-word terms that should be quoted in search queries.
diff --git a/skills/last30days/scripts/lib/reddit.py b/skills/last30days/scripts/lib/reddit.py
index 9cfae9a7..b138e066 100644
--- a/skills/last30days/scripts/lib/reddit.py
+++ b/skills/last30days/scripts/lib/reddit.py
@@ -55,9 +55,10 @@ DEPTH_CONFIG = {
},
}
-from .query import extract_core_subject as _query_extract
+from .query import extract_core_subject as _query_extract, infer_query_intent
from .relevance import token_overlap_relevance, RELEVANCE_FLOOR, MIN_ON_TOPIC
+
# Reddit-specific noise words (preserves original smaller set)
NOISE_WORDS = frozenset({
'best', 'top', 'good', 'great', 'awesome', 'killer',
@@ -104,7 +105,7 @@ def expand_reddit_queries(topic: str, depth: str) -> List[str]:
if core.lower() != original_clean.lower() and len(original_clean.split()) <= 8:
queries.append(original_clean)
- qtype = _infer_query_intent(topic)
+ qtype = infer_query_intent(topic)
# Product queries: always include review-oriented variant to bias toward
# review communities instead of keyword-matching unrelated subreddits.
@@ -126,22 +127,6 @@ def expand_reddit_queries(topic: str, depth: str) -> List[str]:
return queries
-def _infer_query_intent(topic: str) -> str:
- """Tiny local fallback for Reddit query expansion only."""
- text = topic.lower().strip()
- if re.search(r"\b(vs|versus|compare|difference between)\b", text):
- return "comparison"
- if re.search(r"\b(how to|tutorial|guide|setup|step by step|deploy|install|configuration|configure|troubleshoot|troubleshooting|error|errors|fix|debug)\b", text):
- return "how_to"
- if re.search(r"\b(thoughts on|worth it|should i|opinion|review)\b", text):
- return "opinion"
- if re.search(r"\b(pricing|feature|features|best .* for)\b", text):
- return "product"
- if re.search(r"\b(predict|prediction|odds|forecast|chance)\b", text):
- return "prediction"
- return "breaking_news"
-
-
# Known utility/meta subreddits that match queries but aren't discussion subs.
# These get a 0.3x penalty (not banned) in subreddit discovery scoring.
UTILITY_SUBS = frozenset({
@@ -486,7 +471,7 @@ def search_reddit(
config = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
timeframe = config["timeframe"]
- intent = _infer_query_intent(topic)
+ intent = infer_query_intent(topic)
# === Phase 1: Query Expansion ===
queries = expand_reddit_queries(topic, depth)
diff --git a/skills/last30days/scripts/lib/tiktok.py b/skills/last30days/scripts/lib/tiktok.py
index 3178b17c..81e7a39b 100644
--- a/skills/last30days/scripts/lib/tiktok.py
+++ b/skills/last30days/scripts/lib/tiktok.py
@@ -25,6 +25,7 @@ DEPTH_CONFIG = {
# Max words to keep from each caption
CAPTION_MAX_WORDS = 500
+from .query import infer_query_intent
from .relevance import token_overlap_relevance as _compute_relevance
@@ -43,20 +44,6 @@ def _extract_core_subject(topic: str) -> str:
return extract_core_subject(topic, noise=_TIKTOK_NOISE)
-def _infer_query_intent(topic: str) -> str:
- """Tiny local intent classifier for TikTok query expansion."""
- text = topic.lower().strip()
- if re.search(r"\b(vs|versus|compare|difference between)\b", text):
- return "comparison"
- if re.search(r"\b(how to|tutorial|guide|setup|step by step|deploy|install)\b", text):
- return "how_to"
- if re.search(r"\b(thoughts on|worth it|should i|opinion|review)\b", text):
- return "opinion"
- if re.search(r"\b(pricing|feature|features|best .* for)\b", text):
- return "product"
- return "breaking_news"
-
-
def expand_tiktok_queries(topic: str, depth: str) -> List[str]:
"""Generate multiple TikTok search queries from a topic.
@@ -76,7 +63,7 @@ def expand_tiktok_queries(topic: str, depth: str) -> List[str]:
if core.lower() != original_clean.lower() and len(original_clean.split()) <= 8:
queries.append(original_clean)
- qtype = _infer_query_intent(topic)
+ qtype = infer_query_intent(topic)
# Intent-specific TikTok content-type variants
if qtype in ("breaking_news", "opinion"):
diff --git a/skills/last30days/scripts/lib/youtube_yt.py b/skills/last30days/scripts/lib/youtube_yt.py
index 2adbb0a8..cc0b358d 100644
--- a/skills/last30days/scripts/lib/youtube_yt.py
+++ b/skills/last30days/scripts/lib/youtube_yt.py
@@ -57,6 +57,8 @@ def reset_transcript_fetch_stats() -> None:
TRANSCRIPT_MAX_WORDS = 5000
from . import dates, http, log, subproc
+from .query import infer_query_intent
+
from .relevance import token_overlap_relevance as _compute_relevance
# yt-dlp transcript-fetch resilience. A non-zero yt-dlp exit means a real fetch
@@ -236,20 +238,6 @@ def _extract_core_subject(topic: str) -> str:
return extract_core_subject(topic, noise=_YT_NOISE)
-def _infer_query_intent(topic: str) -> str:
- """Tiny local intent classifier for YouTube query expansion."""
- text = topic.lower().strip()
- if re.search(r"\b(vs|versus|compare|difference between)\b", text):
- return "comparison"
- if re.search(r"\b(how to|tutorial|guide|setup|step by step|deploy|install|configure|troubleshoot|error|fix|debug)\b", text):
- return "how_to"
- if re.search(r"\b(thoughts on|worth it|should i|opinion|review)\b", text):
- return "opinion"
- if re.search(r"\b(pricing|feature|features|best .* for)\b", text):
- return "product"
- return "breaking_news"
-
-
def expand_youtube_queries(topic: str, depth: str) -> List[str]:
"""Generate multiple YouTube search queries from a topic.
@@ -269,7 +257,7 @@ def expand_youtube_queries(topic: str, depth: str) -> List[str]:
if core.lower() != original_clean.lower() and len(original_clean.split()) <= 8:
queries.append(original_clean)
- qtype = _infer_query_intent(topic)
+ qtype = infer_query_intent(topic)
# Intent-specific YouTube content-type variants
if qtype == "opinion":
diff --git a/tests/test_query.py b/tests/test_query.py
index 517a3835..a737fcbd 100644
--- a/tests/test_query.py
+++ b/tests/test_query.py
@@ -2,7 +2,12 @@
import unittest
-from lib.query import NOISE_WORDS, extract_compound_terms, extract_core_subject
+from lib.query import (
+ NOISE_WORDS,
+ extract_compound_terms,
+ extract_core_subject,
+ infer_query_intent,
+)
class TestExtractCoreSubject(unittest.TestCase):
@@ -122,6 +127,50 @@ class TestNoiseWordsCompleteness(unittest.TestCase):
self.assertIn(w, NOISE_WORDS)
+
+class TestInferQueryIntent(unittest.TestCase):
+ """Tests for infer_query_intent() — the shared canonical classifier.
+
+ Adapters previously kept five near-duplicate copies with subtle drift
+ (reddit added `prediction` and the longest `how_to` regex; youtube had
+ a partial extension; instagram and tiktok lagged). Canonical here is
+ reddit's superset.
+ """
+
+ def test_comparison(self):
+ self.assertEqual(infer_query_intent("Claude vs Gemini"), "comparison")
+ self.assertEqual(infer_query_intent("difference between X and Y"), "comparison")
+
+ def test_how_to_base(self):
+ self.assertEqual(infer_query_intent("how to deploy Kubernetes"), "how_to")
+ self.assertEqual(infer_query_intent("install nginx"), "how_to")
+ self.assertEqual(infer_query_intent("setup OAuth tutorial"), "how_to")
+
+ def test_how_to_extended_keywords(self):
+ # Bare imperatives covered by reddit's extended regex.
+ self.assertEqual(infer_query_intent("configure DNS"), "how_to")
+ self.assertEqual(infer_query_intent("troubleshoot router"), "how_to")
+ self.assertEqual(infer_query_intent("debug python"), "how_to")
+ self.assertEqual(infer_query_intent("fix kernel panic"), "how_to")
+
+ def test_opinion(self):
+ self.assertEqual(infer_query_intent("thoughts on Claude Code"), "opinion")
+ self.assertEqual(infer_query_intent("should I buy a Pixel"), "opinion")
+
+ def test_product(self):
+ self.assertEqual(infer_query_intent("best laptop for programming"), "product")
+ self.assertEqual(infer_query_intent("Surface pricing"), "product")
+
+ def test_prediction(self):
+ self.assertEqual(infer_query_intent("predict the 2028 election"), "prediction")
+ self.assertEqual(infer_query_intent("odds Trump wins"), "prediction")
+ self.assertEqual(infer_query_intent("forecast Q4 earnings"), "prediction")
+
+ def test_breaking_news_default(self):
+ self.assertEqual(infer_query_intent("Kanye West"), "breaking_news")
+ self.assertEqual(infer_query_intent("OpenAI"), "breaking_news")
+
+
class TestExtractCompoundTerms(unittest.TestCase):
"""Tests for extract_compound_terms()."""
diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.py
index f9d7fd91..ab03d62d 100644
--- a/tests/test_youtube_yt.py
+++ b/tests/test_youtube_yt.py
@@ -424,25 +424,6 @@ class TestExpandYouTubeQueries(unittest.TestCase):
self.assertIn("west", core)
-class TestInferQueryIntent(unittest.TestCase):
- """Tests for _infer_query_intent() classification."""
-
- def test_comparison_intent(self):
- self.assertEqual(youtube_yt._infer_query_intent("Claude vs Gemini"), "comparison")
-
- def test_how_to_intent(self):
- self.assertEqual(youtube_yt._infer_query_intent("how to deploy Kubernetes"), "how_to")
-
- def test_opinion_intent(self):
- self.assertEqual(youtube_yt._infer_query_intent("thoughts on Claude Code"), "opinion")
-
- def test_product_intent(self):
- self.assertEqual(youtube_yt._infer_query_intent("best laptop for programming"), "product")
-
- def test_breaking_news_default(self):
- self.assertEqual(youtube_yt._infer_query_intent("Kanye West"), "breaking_news")
-
-
class TestTranscriptCandidateSortKey(unittest.TestCase):
"""Tests for _transcript_candidate_sort_key recency-boosted ordering."""