Skip to content

Parsa-29/loop-config / skills/last30days

last30days

Flagged

Research what people actually say about any topic in the last 30 days. Pulls posts and engagement from Reddit, X, YouTube, TikTok, Hacker News, Polymarket, GitHub, and the web.

FileKindSize
SKILL.mdskill md127.7 KB
agents/openai.yamlconfig448 B
assets/aging-portrait.jpegbinary2.7 MB
assets/claude-code-rap.mp3binary2.2 MB
assets/dog-as-human.pngbinary2.3 MB
assets/dog-original.jpegbinary3.8 MB
assets/swimmom-mockup.jpegbinary2.6 MB
references/save-html-brief.mdmarkdown5.8 KB
scripts/briefing.pyscript8.1 KB
scripts/build-skill.shexecutablescript1.3 KB
scripts/compare.shexecutablescript2.2 KB
scripts/evaluate_search_quality.pyscript19.3 KB
scripts/last30days.pyscript43.2 KB
scripts/lib/__init__.pyscript29 B
scripts/lib/bird_x.pyscript17.5 KB
scripts/lib/bluesky.pyscript12.1 KB
scripts/lib/categories.pyscript7.5 KB
scripts/lib/chrome_cookies.pyscript10.7 KB
scripts/lib/cluster.pyscript10.8 KB
scripts/lib/competitors.pyscript7.2 KB
scripts/lib/cookie_extract.pyscript14.1 KB
scripts/lib/dates.pyscript3.1 KB
scripts/lib/dedupe.pyscript3.2 KB
scripts/lib/digg.pyscript13.0 KB
scripts/lib/entity_extract.pyscript4.1 KB
scripts/lib/env.pyscript25.3 KB
scripts/lib/fanout.pyscript3.1 KB
scripts/lib/fusion.pyscript8.4 KB
scripts/lib/github.pyscript36.5 KB
scripts/lib/grounding.pyscript11.4 KB
scripts/lib/hackernews.pyscript11.3 KB
scripts/lib/html_render.pyscript17.4 KB
scripts/lib/http.pyscript11.4 KB
scripts/lib/instagram.pyscript18.4 KB
scripts/lib/log.pyscript831 B
scripts/lib/normalize.pyscript19.4 KB
scripts/lib/perplexity.pyscript4.7 KB
scripts/lib/pinterest.pyscript5.2 KB
scripts/lib/pipeline.pyscript44.8 KB
scripts/lib/planner.pyscript30.5 KB
scripts/lib/polymarket.pyscript29.6 KB
scripts/lib/preflight.pyscript4.4 KB
scripts/lib/providers.pyscript15.4 KB
scripts/lib/quality_nudge.pyscript13.1 KB
scripts/lib/query.pyscript3.9 KB
scripts/lib/reddit.pyscript24.1 KB
scripts/lib/reddit_enrich.pyscript9.3 KB
scripts/lib/reddit_keyless.pyscript9.9 KB
scripts/lib/reddit_listing.pyscript6.2 KB
scripts/lib/reddit_public.pyscript9.2 KB
scripts/lib/reddit_rss.pyscript7.6 KB
scripts/lib/reddit_shreddit.pyscript6.3 KB
scripts/lib/relevance.pyscript5.8 KB
scripts/lib/render.pyscript69.9 KB
scripts/lib/rerank.pyscript16.7 KB
scripts/lib/resolve.pyscript12.2 KB
scripts/lib/safari_cookies.pyscript5.6 KB
scripts/lib/schema.pyscript10.9 KB
scripts/lib/setup_wizard.pyscript18.3 KB
scripts/lib/signals.pyscript9.5 KB
scripts/lib/skill_meta.pyscript1.2 KB
scripts/lib/snippet.pyscript1.5 KB
scripts/lib/subproc.pyscript2.7 KB
scripts/lib/threads.pyscript6.6 KB
scripts/lib/tiktok.pyscript20.5 KB
scripts/lib/truthsocial.pyscript5.1 KB
scripts/lib/ui.pyscript25.3 KB
scripts/lib/xai_x.pyscript7.3 KB
scripts/lib/xiaohongshu_api.pyscript5.2 KB
scripts/lib/xquik.pyscript6.7 KB
scripts/lib/xurl_x.pyscript5.2 KB
scripts/lib/youtube_yt.pyscript36.5 KB
scripts/setup-keychain.shexecutablescript3.2 KB
scripts/store.pyscript31.1 KB
scripts/test-v1-vs-v2.shexecutablescript5.8 KB
scripts/test_device_auth.pyscript3.9 KB
scripts/verify_v3.pyscript6.0 KB
scripts/watchlist.pyscript9.1 KB

scripts/lib/perplexity.py

View on GitHub
"""Perplexity Sonar Pro / Deep Research via OpenRouter API.

Queries Perplexity models through OpenRouter for AI-synthesized research
with citation annotations. Returns normalized items with synthesis text
and individual citation entries.
"""

from __future__ import annotations

import sys
from urllib.parse import urlparse

from . import http, log


OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"

MODEL_SONAR_PRO = "perplexity/sonar-pro"
MODEL_DEEP_RESEARCH = "perplexity/sonar-deep-research"


def _log(msg: str):
    log.source_log("Perplexity", msg)


def _domain(url: str) -> str:
    return urlparse(url).netloc.strip().lower()


def search(
    query: str,
    date_range: tuple[str, str],
    config: dict,
    deep: bool = False,
) -> tuple[list[dict], dict]:
    """Search via Perplexity Sonar Pro or Deep Research through OpenRouter.

    Args:
        query: Search topic
        date_range: (from_date, to_date) as YYYY-MM-DD strings
        config: Must contain OPENROUTER_API_KEY
        deep: Use Deep Research model (~$0.90/query) instead of Sonar Pro

    Returns:
        Tuple of (items list, artifact dict).
    """
    api_key = config.get("OPENROUTER_API_KEY")
    if not api_key:
        _log("No OPENROUTER_API_KEY configured, skipping")
        return [], {}

    from_date, to_date = date_range
    model = MODEL_DEEP_RESEARCH if deep else MODEL_SONAR_PRO
    timeout = 120 if deep else 30

    if deep:
        print("[Perplexity] Using Deep Research (~$0.90/query)", file=sys.stderr)

    prompt = (
        f"What has been happening with {query} between {from_date} and {to_date}? "
        "Include specific dates, names, numbers, and sources."
    )

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }

    json_data = {
        "model": model,
        "messages": [{"role": "user", "content": prompt}],
    }

    _log(f"Querying {model} for '{query}' ({from_date} to {to_date})")

    try:
        data = http.post(OPENROUTER_URL, json_data, headers=headers, timeout=timeout)
    except http.HTTPError as e:
        if e.status_code == 401:
            _log("Invalid OpenRouter API key (401)")
        elif e.status_code == 429:
            _log("Rate limited by OpenRouter (429)")
        else:
            _log(f"HTTP error: {e}")
        return [], {}
    except Exception as e:
        _log(f"Request failed: {e}")
        return [], {}

    # Parse response
    choices = data.get("choices", [])
    if not choices:
        _log("No choices in response")
        return [], {}

    synthesis = choices[0].get("message", {}).get("content", "")
    if not synthesis:
        _log("Empty synthesis content")
        return [], {}

    # Extract citations from annotations
    annotations = choices[0].get("message", {}).get("annotations", [])
    citations = []
    for ann in annotations:
        url_citation = ann.get("url_citation", {})
        url = url_citation.get("url", "")
        title = url_citation.get("title", "")
        if url:
            citations.append({"url": url, "title": title})

    # Deduplicate citations by URL
    seen_urls = set()
    unique_citations = []
    for c in citations:
        if c["url"] not in seen_urls:
            seen_urls.add(c["url"])
            unique_citations.append(c)
    citations = unique_citations

    _log(f"Got synthesis ({len(synthesis)} chars) with {len(citations)} citations")

    # Build items list
    items = []

    # Primary item: the synthesis itself
    snippet = synthesis[:2000]
    items.append({
        "id": "PX1",
        "title": f"Perplexity {'Deep Research' if deep else 'Sonar Pro'}: {query}",
        "url": "",
        "source_domain": "perplexity.ai",
        "snippet": snippet,
        "date": to_date,
        "relevance": 0.9,
        "why_relevant": f"AI synthesis of recent activity for '{query}'",
        "engagement": {"citations": len(citations)},
        "metadata": {"citations": citations},
    })

    # Individual items for each citation
    for i, cit in enumerate(citations):
        items.append({
            "id": f"PX{i + 2}",
            "title": cit["title"] or _domain(cit["url"]),
            "url": cit["url"],
            "source_domain": _domain(cit["url"]),
            "snippet": "",
            "date": None,
            "relevance": 0.7,
            "why_relevant": f"Cited in Perplexity synthesis for '{query}'",
            "engagement": {"citations": 1},
            "metadata": {"citations": [cit]},
        })

    artifact = {
        "label": "perplexity",
        "model": model,
        "deep": deep,
        "query": query,
        "synthesisLength": len(synthesis),
        "citationCount": len(citations),
    }

    return items, artifact
add-product-e2e-evalpaperclipai/paperclipAdd or extend a Paperclip full-stack runner E2E workflow, fixture, matcher, or report evidence path for local or Daytona execution.Stars: 115kUpdated Claude CodeCodexVerifiedInstall
add-runner-evalpaperclipai/paperclipAdd or extend a Paperclip Runner protocol evaluation definition, roster, assertion, or report fixture with provenance and narrow validation.Stars: 115kUpdated Claude CodeCodexVerifiedInstall
diagnose-why-work-stoppedpaperclipai/paperclipCompatibility entry point for failed, stalled, looping, or over-recovered Paperclip work. Use fix-failed-paperclip-run for the full diagnosis, regression, repair, real verification, and green-PR workflow; honor an explicitly requested diagnosis-only scope.Stars: 115kUpdated Claude CodeCodexVerifiedInstall
fix-failed-paperclip-runpaperclipai/paperclipDiagnose and fix failed, stuck, slow, or incorrectly blocked Paperclip tasks and runs. Use with a task/run URL or failure report to trace the root cause, prove a regression red then green, check second-order effects, verify the real workflow, and deliver a PR with passing checks.Stars: 115kUpdated Claude CodeCodexVerifiedInstall