Skip to content

CSlawyer1985/legal-skillhub / skills/1688-common-cha88-company-risk

1688-common-cha88-company-risk

Verified

88查企业风险查询与分析工具 —— 专注于中国大陆企业的法务风险查询与分析,覆盖经营异常、行政处罚、监管措施、被执行人、失信被执行人、司法案件等风险类型。支持公司名称、统一社会信用代码、companyId 三种输入方式,自动完成风险查询并输出结构化风险分析总结。 触发场景:仅当用户意图为查询企业风险/法务风险时触发。包括但不限于:企业风险查询、公司风险、经营异常、行政处罚、监管措施、被执行人、失信被执行人、司法风险、风险扫描、风险评估、企业合规审查、风险报告、XX公司有什么风险、XX公司安全吗、XX公司有没有处罚、XX公司被执行过吗。 不触发场景:纯粹的企业信息查询(如查公司、搜企业、工商信息、注册资本、法人代表、股东结构、专利商标等)不应触发本技能,请使用其他 cha88 系列工具。

scripts/_http.py

View on GitHub
#!/usr/bin/env python3
"""
通用 HTTP 客户端

职责:签名注入、自动重试、统一错误映射。
所有 capability 的 service 层通过 api_post() 调用 API,
不再各自处理 HTTP / 重试 / 错误解析。
"""

import json
import re
import time
import logging
from functools import wraps

import requests

from _auth import get_auth_headers
from _errors import AuthError, ParamError, RateLimitError, ServiceError

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger('cha88_http')

BASE_URL = "https://skills-gateway.1688.com"
MAX_RETRIES = 3
RETRY_DELAY_BASE = 1


# ── 重试 ─────────────────────────────────────────────────────────────────────

def _with_retry(max_retries: int = MAX_RETRIES):
    """仅重试 ConnectionError / Timeout,其余异常直接传播"""

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            last_exc = None
            for attempt in range(max_retries):
                try:
                    return func(*args, **kwargs)
                except (requests.exceptions.ConnectionError,
                        requests.exceptions.Timeout) as e:
                    last_exc = e
                    delay = min(RETRY_DELAY_BASE * (2 ** attempt), 10)
                    logger.warning("网络异常(尝试%d/%d): %s, %ds后重试",
                                   attempt + 1, max_retries, e, delay)
                    if attempt < max_retries - 1:
                        time.sleep(delay)
            raise ServiceError(f"网络异常,已重试{max_retries}次: {last_exc}")
        return wrapper
    return decorator


# ── 错误映射 ──────────────────────────────────────────────────────────────────

def _handle_http_error(e: requests.exceptions.HTTPError):
    """HTTP 状态码 → SkillError"""
    status = e.response.status_code if e.response is not None else None
    if status == 401:
        raise AuthError("签名无效或已过期(401)")
    if status == 429:
        raise RateLimitError("请求被限流(429),请稍后重试")
    if status == 400:
        raise ParamError("请求参数不合法(400)")
    raise ServiceError(f"HTTP 错误 {status}")


def _handle_biz_error(result: dict):
    """业务错误(HTTP 200 但 success=false)→ SkillError"""
    msg_code = str(result.get("msgCode") or "")
    msg_info = result.get("msgInfo")
    code_match = re.search(r"\b(400|401|429|500)\b", msg_code)
    normalized = code_match.group(1) if code_match else ""

    if normalized == "401":
        raise AuthError("签名无效(401)")
    if normalized == "429":
        raise RateLimitError("请求被限流(429)")
    if normalized == "400":
        raise ParamError("请求参数不合法(400)")
    if normalized == "500":
        raise ServiceError("服务异常(500),请稍后重试")

    detail = msg_info or msg_code or "未知业务错误"
    raise ServiceError(str(detail))


# ── 公共请求 ──────────────────────────────────────────────────────────────────

@_with_retry()
def api_post(path: str, body: dict = None, timeout: int = 30) -> dict:
    """
    POST 请求 API(自动签名 + 重试 + 错误映射)

    Args:
        path:    API 路径,如 /api/companySearch/1.0.0
        body:    请求体 dict(会 json.dumps)
        timeout: 超时秒数

    Returns:
        API 响应中的 data 字段(dict)

    Raises:
        AuthError / ParamError / RateLimitError / ServiceError
    """
    url = f"{BASE_URL}{path}"
    body_str = json.dumps(body or {}, ensure_ascii=False)

    headers = get_auth_headers("POST", path, body_str)
    if not headers:
        raise AuthError("AK 未配置")

    try:
        resp = requests.post(url, headers=headers, data=body_str.encode("utf-8"), timeout=timeout)
        resp.raise_for_status()
    except requests.exceptions.HTTPError as e:
        _handle_http_error(e)

    result = resp.json()
    if result.get("success") is False:
        _handle_biz_error(result)

    data = result.get("data", {})
    if not isinstance(data, dict):
        raise ServiceError("API 返回结构异常(data 不是对象)")

    return data
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 196kUpdated Claude CodeCodexVerifiedInstall