Coverage for agentos/marketplace/skills/wikipedia/wikipedia.py: 5%
41 statements
« prev ^ index » next coverage.py v7.14.3, created at 2026-07-06 12:29 +0800
« prev ^ index » next coverage.py v7.14.3, created at 2026-07-06 12:29 +0800
1"""
2wikipedia — Wikipedia 搜索与摘要获取(无需 API Key)。
4Category: knowledge
5"""
8def run(action: str, query: str = "", lang: str = "zh") -> str:
9 """Wikipedia 查询工具。action: search/summary/page。lang: zh/en/ja 等。"""
10 import json
11 import urllib.parse
12 import urllib.request
14 if not query:
15 return "[wikipedia] 需要 query 参数"
17 base = f"https://{lang}.wikipedia.org/w/api.php"
19 try:
20 if action == "search":
21 params = urllib.parse.urlencode(
22 {
23 "action": "query",
24 "list": "search",
25 "srsearch": query,
26 "format": "json",
27 "srlimit": 10,
28 }
29 )
30 url = f"{base}?{params}"
31 req = urllib.request.Request(url, headers={"User-Agent": "AgentOS/1.0"})
32 with urllib.request.urlopen(req, timeout=10) as resp:
33 data = json.loads(resp.read())
34 results = data.get("query", {}).get("search", [])
35 if not results:
36 return f"[wikipedia] 未找到 '{query}' 相关条目"
37 lines = [f"Wikipedia 搜索结果 ({len(results)} 条):"]
38 for i, r in enumerate(results):
39 lines.append(f" {i+1}. {r['title']} - {r.get('snippet','')[:80]}...")
40 return "\n".join(lines)
42 if action in ("summary", "page"):
43 # Get page extract
44 params = urllib.parse.urlencode(
45 {
46 "action": "query",
47 "prop": "extracts",
48 "exintro": "1",
49 "explaintext": "1",
50 "titles": query,
51 "format": "json",
52 "exchars": "2000" if action == "summary" else "5000",
53 }
54 )
55 url = f"{base}?{params}"
56 req = urllib.request.Request(url, headers={"User-Agent": "AgentOS/1.0"})
57 with urllib.request.urlopen(req, timeout=10) as resp:
58 data = json.loads(resp.read())
59 pages = data.get("query", {}).get("pages", {})
60 for pid, page in pages.items():
61 if pid == "-1":
62 return f"[wikipedia] 页面 '{query}' 不存在"
63 title = page.get("title", "")
64 extract = page.get("extract", "")
65 if not extract:
66 return f"[wikipedia] 页面 '{title}' 无内容"
67 return f"=== {title} ===\n\n{extract}"
68 return f"[wikipedia] 未找到 '{query}'"
70 return f"[wikipedia] 未知操作: {action}, 支持: search/summary/page"
71 except Exception as e:
72 return f"[wikipedia] 查询失败: {e}"
75__all__ = ["run"]