Wikipedia Error Handling 标志

Wikipedia Error Handling

社区
fuzheado
wikipedia-error-handling

Handle HTTP errors, rate limits, and API failures across Wikimedia services — retry/backoff patterns, error formats, and recovery for the Action API, REST, SPARQL, Lift Wing, and EventStreams

概览

发布者fuzheado
代码仓库Wikipedia-AI-Skills
技能名称wikipedia-error-handling
星标数
27
复刻数
10
附带文件
2
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 2 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 fuzheado 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Wikipedia Error Handling AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/fuzheado/Wikipedia-AI-Skills/tree/main/.claude/skills/wikipedia-error-handling
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/fuzheado/Wikipedia-AI-Skills.git /tmp/Wikipedia-AI-Skills
mkdir -p .claude/skills
cp -r /tmp/Wikipedia-AI-Skills/.claude/skills/wikipedia-error-handling .claude/skills/wikipedia-error-handling
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Wikipedia Error Handling,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Wikipedia Error Handling。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Wikipedia Error Handling 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

⚠️ User-Agent required: All API calls below need a descriptive User-Agent header. See the wikimedia-api-access skill for the correct format and rate-limiting patterns.

💡 Related skills:

  • wikimedia-api-access — User-Agent format, base API endpoints, and general rate limiting patterns
  • wikimedia-ml-services — Lift Wing model errors (422, latency, model not found) — see Known Limitations section
  • wikimedia-eventstreams — SSE connection handling and canary event filtering
  • wikidata — SPARQL-specific rate limits and query optimization

Common workflows that combine multiple APIs are especially vulnerable to the errors documented here — a failure in one step can cascade through the entire pipeline.


Reference: HTTP Status Codes for Wikimedia APIs

CodeMeaningCommon CausesRecovery
200Success—Parse response body
301RedirectUsing http:// instead of https://Use HTTPS
400Bad RequestMissing or invalid parameters, malformed JSON bodyCheck parameter names and values against the API docs. For SPARQL: check query syntax.
403ForbiddenMissing or generic User-Agent (e.g., python-requests/2.x, curl/8.x)Set a descriptive User-Agent with contact info. See wikimedia-api-access.
404Not FoundWrong model name (Lift Wing), non-existent page/revision, wrong endpoint URLCheck the endpoint URL and model name against the API docs.
413Payload Too LargeSPARQL query too long for GET (URL length limit)Use POST with query in body. For wbgetentities: reduce batch size below 50.
422Unprocessable EntityLift Wing model rejects the input: parent_revision_missing on revision 1, missing required fieldSee model-specific error handling below
429Too Many RequestsRate limit exceeded — too many requests per second or per hourRead Retry-After header and wait. Implement backoff (see below).
500Internal Server ErrorTransient server-side failureRetry with backoff (max 3 attempts). If persistent, the API may be down.
502Bad GatewayUpstream service unavailable (common for SPARQL and Lift Wing)Wait and retry with exponential backoff. These are usually transient.
503Service UnavailableService overloaded or under maintenanceWait at least 30s before retrying. Check wikitech status.
504Gateway TimeoutQuery took too long (common for complex SPARQL queries or heavy ML models)Optimize the query, reduce batch size, or increase timeout.

SOP: Rate Limiting (429) — The Most Common Error

How Rate Limiting Works

Wikimedia enforces rate limits at two levels simultaneously — you can hit either limit independently:

ServiceAnonymous LimitAuthenticated LimitGranularity
Action API200 req/s (burst), 50 req/s (sustained)Higher for botsPer IP + User-Agent
REST APINo documented hard limit, but aggressive 429 enforcementSamePer IP + User-Agent
SPARQL (WDQS)1 query per ~second (variable), 60s processing per 60s windowSamePer User-Agent + IP pair
Lift Wing ML50,000 req/h, 15 req/s100,000 req/h, 100 req/s (OAuth)Per IP (anon) or token (auth)
EventStreamsNo rate limit (server pushes data)Same—

⚠️ The 2026 gateway rate-limit classes (see wikimedia-api-access): unidentified (IP only) 10 req/min, compliant UA only 200 req/min, authenticated (bot password + cookies) 2000 req/min, bot-flag/WMCS exempt. Authenticate to get the 2000/min class.

The Three Distinct 429 Flavors (diagnose before retrying)

"429" appears in three different places with three different fixes. Verified 2026-08-10 on a 518-file Commons upload batch:

FlavorWhere it appearsMeaningFix
Client rate limitHTTP 429 from api.php, Retry-After header, MediaWiki-style JSON error bodyGateway/classic limiter hit YOUR requestBack off per Retry-After, authenticate for the 2000/min class, slow the pace
Internal outbound fetchHTTP 200 body containing {"error":{"code":"http-bad-status","info":"There was a problem during the HTTP request: 429 Too Many Requests"}}The API call succeeded; MediaWiki's own backend fetch (e.g. action=upload&url= fetching the image URL) got 429'd upstreamDon't make MediaWiki fetch third-party URLs — fetch client-side and send the bytes (e.g. source_filename instead of source_url)
Third-party CDNPlain HTTP 429 from the CDN (e.g. live.staticflickr.com) on YOUR direct downloadPer-IP window on the image CDN, unrelated to WikimediaPause; the window lasts ~60 min after the last 429 and probes can extend it — go fully quiet, then resume (see the flickr skill)

How to tell them apart: a requests-layer spy on requests.sessions.Session.send reveals the real HTTP status; the http-bad-status envelope inside a 200 response is the internal-fetch flavor. meta=userinfo&uiprop=ratelimits (authenticated) shows whether the account itself has any classic limits (hits/max/window, None = none apply).

The Universal Retry Pattern

python
import time
import requests

def api_call_with_retry(url, params=None, data=None, method="GET", max_retries=3):
    """Make an API call with exponential backoff on 429/5xx."""
    headers = {
        "User-Agent": "MyBot/1.0 (https://example.com; user@example.com) ProjectName"
    }
    
    for attempt in range(max_retries):
        if method == "GET":
            resp = requests.get(url, params=params, headers=headers, timeout=30)
        else:
            resp = requests.post(url, json=data, headers=headers, timeout=30)
        
        if resp.status_code == 200:
            return resp.json()
        
        if resp.status_code == 429:
            retry_after = int(resp.headers.get("Retry-After", 60))
            wait = retry_after * (2 ** attempt)  # Exponential backoff
            print(f"Rate limited. Waiting {wait}s (attempt {attempt+1}/{max_retries})")
            time.sleep(wait)
            continue
        
        if 500 <= resp.status_code < 600:
            wait = (2 ** attempt) * 5
            print(f"Server error {resp.status_code}. Retrying in {wait}s")
            time.sleep(wait)
            continue
        
        # 400, 403, 404, 422 — don't retry, fix the request
        resp.raise_for_status()
    
    raise Exception(f"API call failed after {max_retries} retries. Last status: {resp.status_code}")

Connection Reuse (Prevents Rate Limits)

python
# Good: reuse the same session (reuses TCP connections, reduces load)
session = requests.Session()
session.headers.update({
    "User-Agent": "MyBot/1.0 (https://example.com; user@example.com) ProjectName"
})

# Make many calls through the same session:
for item in items:
    resp = session.get(API_URL, params=params)
    # ...

Concurrent Workers and Burst Rate Limits

When scraping many language editions concurrently (e.g., fetching the same article from 300+ {lang}.wikipedia.org domains), the combined request rate can trigger 429s even though each individual session stays under the limit. This happens because Wikimedia enforces rate limits per IP, not per domain — hitting 300 different Wikipedia domains from one IP address still counts as one sustained stream.

Symptoms:

  • First 50–100 requests succeed, then a burst of 429s
  • Earlier requests in the batch succeed, later ones fail
  • The rate limit is triggered by sustained rate, not total requests

Quantify the budget before tuning workers. The gateway limits are per minute per client class (10 / 200 / 2000 req/min — see wikimedia-api-access), so work out the rate your concurrency actually produces: 6 unpaced workers sustain ~360/min (6 × 60) against a 200/min UA-only budget, while a 1s wave gate admitting 4 parallel requests is ~240/min. A handful of requests fired back-to-back return 200s, so a burst probe cannot tell you whether the sustained run is safe. And if 429s appear right after a caching or batching change, suspect a cache-key invalidation (batch composition is part of a URL-derived key) rather than a real traffic increase — see Cache the entity, not the batch in wikimedia-api-access.

Prevention strategies (in order of effectiveness):

  1. Reduce concurrent workers — 6 workers is safer than 12 for large jobs:

    python
    with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:
        futures = {executor.submit(fetch, l, t): (l, t) for l, t in languages}
  2. Add jitter between batch submissions — Instead of submitting all futures at once, stagger them slightly:

    python
    import time, random
    futures = {}
    for i, (lang, title) in enumerate(languages):
        futures[executor.submit(fetch, lang, title)] = (lang, title)
        if i > 0 and i % 20 == 0:
            time.sleep(random.uniform(0.5, 1.5))  # brief pause every 20
  3. Cache aggressively — Many use cases involve re-checking the same articles. Cache results to disk so that re-runs (e.g., with different parameters) skip HTTP entirely. A simple {lang}:{title} → {response_text} JSON file works well for this.

Retry pattern for 429 with concurrent workers:

python
def fetch_with_retry(lang, title):
    """Fetch with exponential backoff on 429."""
    import time
    url = f"https://{lang}.wikipedia.org/api/rest_v1/page/summary/{title}"
    for attempt in range(4):
        resp = requests.get(url, headers=HEADERS, timeout=15)
        if resp.status_code == 200:
            return resp.json().get('extract')
        if resp.status_code == 429:
            retry_after = int(resp.headers.get('Retry-After', 2))
            time.sleep(retry_after + (2 ** attempt))  # backoff + Retry-After
            continue
        return None  # Other errors (404, etc.) are final
    return None

SPARQL-Specific Rate Limiting

The Wikidata SPARQL endpoint has its own stricter limits (see the wikidata skill for details). Key rules:

  • 60-second timeout per query (hard limit)
  • 1 query per ~second sustained (slower than other APIs)
  • 429 includes Retry-After header — respect it
  • 429 without Retry-After — wait at least 60 seconds
  • Use POST for long queries (URL length limit on GET)
python
def sparql_query(query, max_retries=3):
    """Execute a SPARQL query with WDQS-specific rate limit handling."""
    url = "https://query.wikidata.org/sparql"
    headers = {
        "User-Agent": "MyBot/1.0 (https://example.com; user@example.com) ProjectName",
        "Accept": "application/sparql-results+json",
    }
    
    for attempt in range(max_retries):
        # Use POST for long queries
        resp = requests.get(url, params={"format": "json", "query": query},
                          headers=headers, timeout=60)
        
        if resp.status_code == 200:
            return resp.json()
        
        if resp.status_code == 429:
            retry_after = int(resp.headers.get("Retry-After", 60))
            wait = max(retry_after, 10) * (2 ** attempt)
            print(f"SPARQL rate limited — waiting {wait}s")
            time.sleep(wait)
            continue
        
        if resp.status_code == 503:
            time.sleep(30 * (2 ** attempt))
            continue
        
        resp.raise_for_status()
    
    raise Exception("SPARQL query failed after retries")

SOP: User-Agent Errors (403)

Detection

python
# If you get a 403, the most common cause is a missing or generic User-Agent
if resp.status_code == 403:
    print("403 Forbidden — likely missing or generic User-Agent")
    print("Set a descriptive User-Agent: 'MyBot/1.0 (contact@example.com) ProjectName'")

Blocked User-Agent Strings

The following User-Agent strings are always blocked by Wikimedia:

  • python-requests/2.x (any version)
  • curl/8.x (any version)
  • Wget/1.x
  • Python-urllib/3.x
  • Java/1.x
  • Any empty or missing User-Agent header

Correct User-Agent Format

<client-name>/<version> (<contact-info>) <project-name>

Examples:

MyBot/1.0 (https://example.com; bot@example.com) CategoryAnalysis
WikipediaQualityChecker/2.1 (https://meta.wikimedia.org; user@example.com) ABTesting

See the wikimedia-api-access skill for full details.


SOP: Lift Wing ML Model Errors

Lift Wing models have model-specific error responses that are not covered by standard HTTP codes.

422: Parent Revision Missing (New Pages)

Applies to: revertrisk-language-agnostic, revertrisk-multilingual, revertrisk-wikidata

Cause: Brand-new pages (revision 1) have no parent revision for the revert-risk model to compare against.

Detection:

python
resp = requests.post(url, json=data, headers=headers, timeout=30)
if resp.status_code == 422:
    error = resp.json()
    if "parent_revision_missing" in str(error):
        print("Revision 1 cannot be scored by revert-risk models")
        # Fall back to articlequality model

Workaround: Use the articlequality model instead (it scores the revision itself, not the diff):

python
fallback_url = "https://api.wikimedia.org/service/lw/inference/v1/models/articlequality:predict"
fallback_data = {"rev_id": rev_id, "lang": "en"}

Note: The articlequality model has ~60s processing latency for brand-new revisions (see Known Limitations in wikimedia-ml-services).

422: Missing Required Field

Applies to: All Lift Wing models

Cause: Required field is missing from the request body (e.g., rev_id, lang, title).

Fix: Check the model's documented required fields. Common required fields by model:

ModelRequired Fields
revertrisk-language-agnosticrev_id (int), lang (string)
articlequalityrev_id (int), lang (string)
outlink-topic-modelpage_title (string), lang (string)
article-countrytitle (string — note: not page_title), lang (string)

404: Model Not Found

Cause: The model name in the URL is wrong, or the wiki code is wrong.

Common mistakes:

  • Using enwiki-articlequality instead of the modern articlequality (note: the modern model is just articlequality, not articlequality-language-agnostic)
  • Using a wiki code that doesn't have this model deployed (check the model list)
  • Including .predict in the wrong place

Empty Scores (Articlequality Latency)

Applies to: articlequality, {wiki}-articlequality

Cause: Revision is less than ~60 seconds old and hasn't been indexed by the model yet.

Response when this happens:

json
{
  "enwiki": {
    "models": {"articlequality": {"version": "0.9.2"}},
    "scores": {}  # Empty — no score for this revision yet
  }
}

Workaround: Retry with a delay:

python
def score_with_retry(rev_id, max_attempts=3, delay=30):
    for attempt in range(max_attempts):
        result = call_articlequality(rev_id)
        scores = result.get("enwiki", {}).get("scores", {})
        if str(rev_id) in scores:
            return scores[str(rev_id)]
        print(f"Score not ready yet (attempt {attempt+1}). Waiting {delay}s...")
        time.sleep(delay)
    return None  # Score unavailable

SOP: EventStreams Connection Errors

Connection Drops

Cause: EventStreams has a 15-minute idle timeout. The server closes the connection if no events arrive.

Detection: The SSE stream's events() generator stops yielding events, or the HTTP connection raises ConnectionError/ChunkedEncodingError.

Recovery: Reconnect with exponential backoff:

python
import time
from sseclient import SSEClient

def consume_eventstream(url, max_reconnects=5):
    for attempt in range(max_reconnects):
        try:
            messages = SSEClient(url)
            for msg in messages:
                if msg.event == 'message':
                    yield msg
        except (ConnectionError, ChunkedEncodingError) as e:
            wait = min(30, 2 ** attempt)  # Cap at 30s
            print(f"Connection lost: {e}. Reconnecting in {wait}s...")
            time.sleep(wait)

No Events (Silent Connection Drop)

Detection: The connection opens (HTTP 200) but no events arrive even though the stream should be active. This can happen if the stream name is wrong.

Debugging:

python
# Wrong: silent failure
url = "https://stream.wikimedia.org/v2/stream/wrong-stream-name"
# Correct: should receive events immediately
url = "https://stream.wikimedia.org/v2/stream/recentchange"

Fix: Verify the stream name against the stream catalog and the wikimedia-eventstreams skill.

Canary Events

Applies to: All EventStreams streams

Detection: Events with meta.domain == "canary" are test events injected by WMF infrastructure.

Handling: Always filter them out:

python
if event.get("meta", {}).get("domain") == "canary":
    continue  # Discard — this is a test event

SOP: SPARQL Errors

Query Timeout (HTTP 504)

Cause: Query exceeds the 60-second hard limit.

Symptoms: Empty results after a long wait, or HTTP 504 Gateway Timeout.

Fixes:

  • Add LIMIT clause to reduce result set size
  • Remove SERVICE wikibase:label temporarily and add it back after optimizing
  • Add appropriate FILTER clauses to narrow the search space
  • Use values clauses to restrict to known item sets

Query Syntax Error (HTTP 400)

Cause: Invalid SPARQL syntax.

Debugging:

python
if resp.status_code == 400:
    print("SPARQL syntax error. Check:")
    print("  1. All prefixes are declared (wd:, wdt:, p:, ps:, etc.)")
    print("  2. Curly braces are balanced")
    print("  3. FILTER syntax is correct")
    print("  4. String literals use quotes correctly")
    print(f"Response: {resp.text[:500]}")  # Error message often hints at the issue

Empty SPARQL Results

Cause: The query is syntactically valid but returns no results. This is not an error, but can be confusing.

Common reasons:

  • Wrong Q/P IDs (e.g., Q38104 = Nobel Prize in Physics, not Q38105)
  • Wrong property (e.g., P166 = award received, not P106)
  • No data exists for the combination you're querying
  • Case sensitivity: property values may be case-sensitive

Debugging: Test the query in the WDQS web UI first.


SOP: General Debugging Strategy

When any Wikimedia API call fails, follow this checklist:

  1. Check the HTTP status code — see the reference table at the top of this skill
  2. Check the User-Agent header — is it descriptive? (see wikimedia-api-access)
  3. Check the endpoint URL — is it correct for this API?
  4. Check the request parameters — are all required fields present? Correct types?
  5. Check for rate limiting — did you make too many requests too quickly?
  6. Check the API documentation — has the API changed? (check the relevant skill)
  7. Check network connectivity — can you reach the endpoint at all? (curl -I <url>)
  8. Check for transient failures — try again after a short delay

API-Specific Error Response Examples

Action API error response:

json
{
  "error": {
    "code": "missingparam",
    "info": "The \"titles\" parameter must be set.",
    "*": "See https://en.wikipedia.org/w/api.php for API usage"
  }
}

Lift Wing ML error response:

json
{
  "error": "Model 'enwiki-nonexistent-model' not found",
  "error_type": "ModelNotFoundError"
}

SPARQL error response:

json
{
  "error": "org.apache.jena.query.QueryParseException: ..."
}

Logging Pattern for Debugging

python
import logging
logging.basicConfig(level=logging.DEBUG)

# Log every API call for debugging
session = requests.Session()
session.hooks['response'].append(
    lambda r, *args, **kwargs: logging.debug(
        f"{r.request.method} {r.url} → {r.status_code} ({len(r.content)} bytes)"
    )
)

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Wikipedia Error Handling AI 技能有什么作用?

Handle HTTP errors, rate limits, and API failures across Wikimedia services — retry/backoff patterns, error formats, and recovery for the Action API, REST, SPARQL, Lift Wing, and EventStreams

为什么在 TypingMind 中使用 Wikipedia Error Handling?

因为您只需安装一次,就能搭配任何模型使用。Wikipedia Error Handling 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Wikipedia Error Handling?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/fuzheado/Wikipedia-AI-Skills/tree/main/.claude/skills/wikipedia-error-handling。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Wikipedia Error Handling?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Wikipedia Error Handling 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Wikipedia Error Handling 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Wikipedia Error Handling AI 技能免费吗?

是的。fuzheado 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇