Skip to content

Dianel555/DSkills / skills/grok-search

grok-search

Verified

Enhanced web search and real-time content retrieval via Grok API with forced tool routing. Use when: (1) Web search / information retrieval / fact-checking, (2) Webpage content extraction / URL parsing, (3) Breaking knowledge cutoff limits for current information, (4) Real-time news and technical documentation, (5) Multi-source information aggregation. Triggers: "search for", "find information about", "latest news", "current", "fetch webpage", "get content from URL". IMPORTANT: This skill REPLACES built-in WebSearch/WebFetch with Grok Search tools.

scripts/groksearch/provider.py

View on GitHub
import json
import sys
from datetime import UTC, datetime

from .config import config
from .http import get_http_client, retry_attempts
from .prompts import FETCH_PROMPT, SEARCH_PROMPT


def _get_local_time_info() -> str:
    try:
        local_tz = datetime.now().astimezone().tzinfo
        local_now = datetime.now(local_tz)
    except Exception:
        local_now = datetime.now(UTC)

    weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    return (
        f"[Current Time Context]\n"
        f"- Date: {local_now.strftime('%Y-%m-%d')} ({weekdays[local_now.weekday()]})\n"
        f"- Time: {local_now.strftime('%H:%M:%S')}\n"
    )


def _needs_time_context(query: str) -> bool:
    keywords = [
        "current",
        "now",
        "today",
        "tomorrow",
        "yesterday",
        "this week",
        "last week",
        "next week",
        "latest",
        "recent",
        "recently",
        "up-to-date",
        "当前",
        "现在",
        "今天",
        "最新",
        "最近",
    ]
    query_lower = query.lower()
    return any(kw in query_lower or kw in query for kw in keywords)


class GrokSearchProvider:
    def __init__(self, api_url: str, api_key: str, model: str):
        self.api_url = api_url.rstrip("/")
        self.api_key = api_key
        self.model = model
        self._headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }

    async def search(self, query: str, platform: str = "", min_results: int = 3, max_results: int = 10) -> str:
        platform_prompt = f"\n\nFocus on platforms: {platform}" if platform else ""
        return_prompt = f"\n\nReturn {min_results}-{max_results} results as JSON array."
        time_context = _get_local_time_info() + "\n" if _needs_time_context(query) else ""

        payload = {
            "model": self.model,
            "messages": [
                {"role": "system", "content": SEARCH_PROMPT},
                {"role": "user", "content": time_context + query + platform_prompt + return_prompt},
            ],
        }

        # Enable web search for supported endpoints
        if "openrouter" not in config.grok_api_url:
            # xAI native and compatible endpoints: explicit tools array
            payload["tools"] = [{"type": "web_search"}]

        return await self._execute(payload)

    async def fetch(self, url: str) -> str:
        payload = {
            "model": self.model,
            "messages": [
                {"role": "system", "content": FETCH_PROMPT},
                {"role": "user", "content": f"{url}\n\nFetch and return structured Markdown."},
            ],
        }
        return await self._execute(payload)

    async def _execute(self, payload: dict) -> str:
        try:
            content = await self._execute_stream(payload)
            if not content:
                raise ValueError("Streaming response returned empty content")
            return content
        except Exception as e:
            if config.debug_enabled:
                print(f"[DEBUG] Streaming failed: {e}, falling back to non-streaming", file=sys.stderr)
            return await self._execute_non_stream(payload)

    async def _execute_non_stream(self, payload: dict) -> str:
        payload_copy = {**payload, "stream": False}
        client = await get_http_client()

        async for attempt in retry_attempts(config):
            with attempt:
                response = await client.post(
                    f"{self.api_url}/chat/completions",
                    headers=self._headers,
                    json=payload_copy,
                )
                response.raise_for_status()
                data = response.json()
                choices = data.get("choices", [])
                if choices:
                    return choices[0].get("message", {}).get("content", "")
                return ""

    async def _execute_stream(self, payload: dict) -> str:
        payload_copy = {**payload, "stream": True}
        client = await get_http_client()

        async for attempt in retry_attempts(config):
            with attempt:
                async with client.stream(
                    "POST",
                    f"{self.api_url}/chat/completions",
                    headers=self._headers,
                    json=payload_copy,
                ) as response:
                    response.raise_for_status()
                    return await self._parse_streaming_response(response)

    async def _parse_streaming_response(self, response) -> str:
        content = ""
        full_body_buffer = []

        async for line in response.aiter_lines():
            line = line.strip()
            if not line:
                continue
            full_body_buffer.append(line)

            if line.startswith("data:"):
                if line in ("data: [DONE]", "data:[DONE]"):
                    continue
                try:
                    json_str = line[5:].lstrip()
                    data = json.loads(json_str)
                    choices = data.get("choices", [])
                    if choices:
                        delta = choices[0].get("delta", {})
                        if "content" in delta:
                            content += delta["content"]
                except (json.JSONDecodeError, IndexError):
                    continue

        if not content and full_body_buffer:
            try:
                full_text = "".join(full_body_buffer)
                data = json.loads(full_text)
                if "choices" in data and data["choices"]:
                    message = data["choices"][0].get("message", {})
                    content = message.get("content", "")
            except json.JSONDecodeError:
                pass

        return content
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: 472kUpdated 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