Skip to content

Dianel555/DSkills / skills/exa

High-precision semantic search and content retrieval via Exa API. Use when: (1) Deep research requiring semantic understanding, (2) Code documentation and examples lookup, (3) Company/professional research, (4) AI-powered comprehensive research tasks, (5) URL content extraction with structured output. Triggers: "research", "find papers", "code examples", "company info", "LinkedIn profiles", "deep analysis". Differentiator: Exa excels at semantic/neural search while grok-search is better for real-time news and general web content.

scripts/exa_cli/client.py

View on GitHub
"""HTTP client with bounded retry and Retry-After support."""

from __future__ import annotations

import json
import re
import sys
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from typing import Any
from urllib.parse import quote

import httpx
from tenacity import AsyncRetrying, retry_if_exception, stop_after_attempt
from tenacity.wait import wait_base, wait_random_exponential

RETRYABLE_STATUS_CODES = {408, 429, 500, 502, 503, 504}
RUN_ID_RE = re.compile(r"^agent_run_[A-Za-z0-9_-]+$")


def _is_retryable_exception(exc: BaseException) -> bool:
    if isinstance(exc, (httpx.TimeoutException, httpx.NetworkError, httpx.ConnectError)):
        return True
    if isinstance(exc, httpx.HTTPStatusError):
        return exc.response.status_code in RETRYABLE_STATUS_CODES
    return False


def _debug_log(event: dict) -> None:
    """Emit a single JSON line to stderr; never includes auth values."""
    print(json.dumps(event, ensure_ascii=False), file=sys.stderr)


class _WaitWithRetryAfter(wait_base):
    """tenacity wait that prefers `Retry-After` on 429, capped to `max_wait`."""

    def __init__(self, max_wait: int, debug: bool = False):
        self._max_wait = max_wait
        self._base_wait = wait_random_exponential(multiplier=1, max=max_wait)
        self._debug = debug

    def __call__(self, retry_state) -> float:
        wait_seconds = self._base_wait(retry_state)
        if retry_state.outcome and retry_state.outcome.failed:
            exc = retry_state.outcome.exception()
            if isinstance(exc, httpx.HTTPStatusError) and exc.response.status_code == 429:
                parsed = self._parse_retry_after(exc.response)
                if parsed is not None:
                    wait_seconds = min(parsed, float(self._max_wait))
        wait_seconds = min(float(wait_seconds), float(self._max_wait))
        if self._debug:
            _debug_log(
                {
                    "event": "retry_wait",
                    "attempt": retry_state.attempt_number,
                    "wait_seconds": wait_seconds,
                    "max_wait": self._max_wait,
                }
            )
        return wait_seconds

    def _parse_retry_after(self, response: httpx.Response) -> float | None:
        header = response.headers.get("Retry-After")
        if not header:
            return None
        header = header.strip()
        if header.isdigit():
            return float(header)
        try:
            retry_dt = parsedate_to_datetime(header)
            if retry_dt.tzinfo is None:
                retry_dt = retry_dt.replace(tzinfo=UTC)
            delay = (retry_dt - datetime.now(UTC)).total_seconds()
            return max(0.0, delay)
        except (TypeError, ValueError):
            return None


class ExaClient:
    """Async client wrapping POST/GET to Exa API with retry + Retry-After cap."""

    def __init__(
        self,
        api_url: str,
        api_key: str,
        max_retry_wait: int = 60,
        debug: bool = False,
        auth_scheme: str = "x-api-key",
        transport: httpx.AsyncBaseTransport | None = None,
        retry_sleep=None,
    ):
        self.api_url = api_url.rstrip("/")
        self.api_key = api_key
        self.max_retry_wait = max_retry_wait
        self.debug = debug
        self.auth_scheme = auth_scheme
        self.timeout = httpx.Timeout(connect=15.0, read=60.0, write=15.0, pool=None)
        client_args = {
            "timeout": self.timeout,
            "follow_redirects": True,
        }
        if transport is not None:
            client_args["transport"] = transport
        self._client = httpx.AsyncClient(**client_args)
        self._retry_sleep = retry_sleep

    async def __aenter__(self) -> ExaClient:
        await self._client.__aenter__()
        return self

    async def __aexit__(self, exc_type, exc, traceback) -> None:
        await self._client.__aexit__(exc_type, exc, traceback)

    @property
    def is_closed(self) -> bool:
        return bool(getattr(self._client, "is_closed", False))

    def _headers(self, *, agent: bool = False) -> dict[str, str]:
        if self.auth_scheme == "bearer":
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json",
            }
        else:
            headers = {
                "x-api-key": self.api_key,
                "Content-Type": "application/json",
            }
        if agent:
            headers["Exa-Beta"] = "agent-2026-05-07"
        return headers

    async def _send_json(
        self,
        method: str,
        path: str,
        json_body: dict | None = None,
        *,
        agent: bool = False,
    ) -> dict[str, Any]:
        url = f"{self.api_url}{path}"
        upper_method = method.upper()
        if self.debug:
            _debug_log({"event": "request", "method": upper_method, "url": url})
        if upper_method == "GET":
            response = await self._client.get(url, headers=self._headers(agent=agent))
        else:
            response = await self._client.post(url, headers=self._headers(agent=agent), json=json_body or {})
        response.raise_for_status()
        return response.json()

    async def _request_json(
        self,
        method: str,
        path: str,
        json_body: dict | None = None,
        *,
        agent: bool = False,
    ) -> dict[str, Any]:
        retry_args = {
            "stop": stop_after_attempt(4),
            "wait": _WaitWithRetryAfter(self.max_retry_wait, debug=self.debug),
            "retry": retry_if_exception(_is_retryable_exception),
            "reraise": True,
        }
        if self._retry_sleep is not None:
            retry_args["sleep"] = self._retry_sleep
        async for attempt in AsyncRetrying(**retry_args):
            with attempt:
                return await self._send_json(method, path, json_body, agent=agent)

    async def search(self, body: dict[str, Any]) -> dict[str, Any]:
        return await self._request_json("POST", "/search", body)

    async def get_contents(self, ids: list[str], extras: dict[str, Any] | None = None) -> dict[str, Any]:
        # Upstream payload field is `ids`, not `urls` (see webFetch.ts:64).
        body: dict[str, Any] = {"ids": ids}
        if extras:
            body.update(extras)
        return await self._request_json("POST", "/contents", body)

    async def agent_create(self, body: dict[str, Any]) -> dict[str, Any]:
        return await self._send_json("POST", "/agent/runs", body, agent=True)

    async def agent_get(self, run_id: str) -> dict[str, Any]:
        if not RUN_ID_RE.fullmatch(run_id):
            raise ValueError("run ID must match ^agent_run_[A-Za-z0-9_-]+$")
        encoded_id = quote(run_id, safe="")
        return await self._request_json("GET", f"/agent/runs/{encoded_id}", agent=True)
rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).Stars: 198kUpdated Claude CodeCodexUnverifiedInstall
doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.Stars: 198kUpdated Claude CodeCodexVerifiedInstall