跳转至内容

开发工具(Devkit:Mock 与诊断)

dashscope.devkit 提供两个可选的开发辅助能力,关闭时几乎零开销, 生产成功路径上不会导入本包。

  • Dev mock —— static / replay / record 三种模式在传输层 拦截 HTTP 请求,仅覆盖 HTTP,不覆盖 WebSocket 传输。 代码中用 dashscope.enable_dev_mock(...) 启用, 或设置 DASHSCOPE_DEV_MOCK=<mode>。各模式能力范围见下表。
  • 自诊断 —— 本地双语规则表,把失败调用转化为结构化的修复建议, 通过 DashScopeError.diagnosis 呈现。
模式 网络 能力范围
static 离线 仅 chat / multimodal 的解析冒烟:本地合成响应,走通协议适配、SSE 解析与类型化模型。不模拟工具调用、结构化输出或任务状态机;其他资源(向量、rerank 等)会抛出 DevMockMiss
replay 离线 回放录制的真实响应;未命中抛出 DevMockMiss,不会回落到网络
record 真实请求 透传真实服务并录制响应,可能产生费用,供后续离线回放
WebSocket — 三种模式均不覆盖

根模块转发了 mock 开关:dashscope.enable_dev_mock、 dashscope.disable_dev_mock、dashscope.dev_mock_active。

共享录制文件

record 模式会把完整真实响应写盘,可能包含生成内容、 工具调用参数或账号数据。共享 fixture 前先用 set_redactor 注册脱敏器,但注意:脱敏器只处理能解析为单个 JSON 文档的 响应体,SSE 流与二进制响应原样落盘、不会被脱敏—— 注册脱敏器不等于所有 fixture 都已脱敏。

Dev mock 开关

enable_dev_mock

enable_dev_mock(
    mode: str = "static", fixture_path: Optional[str] = None
) -> None

Turn on the dev mock process-wide (static / replay / record).

Source code in dashscope/devkit/__init__.py
44
45
46
47
48
49
def enable_dev_mock(
    mode: str = "static",
    fixture_path: Optional[str] = None,
) -> None:
    """Turn on the dev mock process-wide (``static`` / ``replay`` / ``record``)."""
    enable(mode, fixture_path)

disable_dev_mock

disable_dev_mock() -> None

Turn the dev mock back off.

Source code in dashscope/devkit/__init__.py
52
53
54
def disable_dev_mock() -> None:
    """Turn the dev mock back off."""
    disable()

is_active

is_active() -> bool

Whether the dev mock is currently active (code or env activation).

Source code in dashscope/devkit/__init__.py
57
58
59
def is_active() -> bool:
    """Whether the dev mock is currently active (code or env activation)."""
    return active()

DevMockMiss

DevMockMiss(
    message: str,
    *,
    code: Optional[str] = None,
    status_code: Optional[int] = None,
    request_id: Optional[str] = None,
    body: Any = None,
    headers: Optional[Mapping[str, str]] = None
)

Bases: DashScopeError

Replay has no recorded response, or static cannot synthesize one.

Subclasses the v2 error base, so except DashScopeError covers it.

Source code in dashscope/errors.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def __init__(
    self,
    message: str,
    *,
    code: Optional[str] = None,
    status_code: Optional[int] = None,
    request_id: Optional[str] = None,
    body: Any = None,
    headers: Optional[Mapping[str, str]] = None,
) -> None:
    super().__init__(message)
    self.message = message
    self.code = code
    self.status_code = status_code
    self.request_id = request_id
    self.body = body
    self.headers = headers or {}

set_redactor

set_redactor(fn: Optional[Callable[[Any], Any]]) -> None

Register a hook that scrubs a recorded JSON body before it is saved.

Record mode persists the full response body, which can contain generated content, tool-call arguments or account fields. The redactor receives the parsed JSON (dict / list) and returns the value to write. It runs only when the body parses as a single JSON document -- SSE streams and binary bodies are stored verbatim, so scrub those at the source or do not record them. Pass None to clear.

Source code in dashscope/devkit/mock.py
85
86
87
88
89
90
91
92
93
94
95
96
97
def set_redactor(fn: Optional[Callable[[Any], Any]]) -> None:
    """Register a hook that scrubs a recorded JSON body before it is saved.

    Record mode persists the full response body, which can contain
    generated content, tool-call arguments or account fields. The
    redactor receives the parsed JSON (``dict`` / ``list``) and returns
    the value to write. It runs only when the body parses as a single
    JSON document -- SSE streams and binary bodies are stored verbatim,
    so scrub those at the source or do not record them. Pass ``None`` to
    clear.
    """
    global _redactor
    _redactor = fn

自诊断

Diagnosis dataclass

Diagnosis(
    title: str,
    fixes: Tuple[Tuple[str, str], ...],
    command: str = "",
)

A matched diagnosis: title, (cause, fix) pairs, optional command.

title instance-attribute

title: str

fixes instance-attribute

fixes: Tuple[Tuple[str, str], ...]

command class-attribute instance-attribute

command: str = ''

diagnose

diagnose(
    status_code: Optional[int] = None,
    code: Optional[str] = None,
    message: Optional[str] = None,
) -> Optional[Diagnosis]

Match a failure against the local rule table.

First matching rule wins; rules are ordered most-specific first. The returned Diagnosis is in the language selected by DASHSCOPE_DIAGNOSIS_LANG (default zh).

Source code in dashscope/devkit/diagnosis.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
def diagnose(
    status_code: Optional[int] = None,
    code: Optional[str] = None,
    message: Optional[str] = None,
) -> Optional[Diagnosis]:
    """Match a failure against the local rule table.

    First matching rule wins; rules are ordered most-specific first.
    The returned Diagnosis is in the language selected by
    ``DASHSCOPE_DIAGNOSIS_LANG`` (default zh).
    """
    code_lower = (code or "").lower()
    msg = str(message or "")
    for rule in RULES:
        if any(
            _match_one(m, status_code, code_lower, msg) for m in rule.matchers
        ):
            if _lang() == "en":
                return rule.diagnosis_en
            return rule.diagnosis_zh
    return None

render

render(
    diagnosis: Diagnosis, lang: Optional[str] = None
) -> str

Render a diagnosis as a terminal block.

Ends with an escalation hint to the built-in AI expert.

Source code in dashscope/devkit/diagnosis.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
def render(diagnosis: Diagnosis, lang: Optional[str] = None) -> str:
    """Render a diagnosis as a terminal block.

    Ends with an escalation hint to the built-in AI expert.
    """
    lang = lang or _lang()
    if lang == "zh":
        title_line = f"💡 [DashScope 诊断建议] {diagnosis.title}"
        causes_line = "🔍 可能的原因与修复方法:"
    else:
        title_line = f"💡 [DashScope Diagnosis] {diagnosis.title}"
        causes_line = "🔍 Possible causes and fixes:"
    lines = ["=" * _WIDTH, title_line, "", causes_line]
    for i, (cause, fix) in enumerate(diagnosis.fixes, 1):
        lines.append(f"  {i}. {cause}")
        lines.append(f"     👉 {fix}")
    if diagnosis.command:
        label = "🛠️ 快捷命令:" if lang == "zh" else "🛠️ Quick check: "
        lines += ["", f"{label}{diagnosis.command}"]
    lines += ["", _EXPERT_HINT[lang]]
    lines.append("=" * _WIDTH)
    return "\n".join(lines)

install_excepthook

install_excepthook() -> None

Append the diagnosis block to uncaught tracebacks (stderr only).

The normal traceback still prints first; the diagnosis is advisory output appended after it. Idempotent.

Chains to whatever sys.excepthook was installed before this call (not sys.__excepthook__), so a third-party hook already in place -- pytest, IPython, an APM agent -- keeps running instead of being silently dropped.

Source code in dashscope/devkit/diagnosis.py
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
def install_excepthook() -> None:
    """Append the diagnosis block to uncaught tracebacks (stderr only).

    The normal traceback still prints first; the diagnosis is advisory
    output appended after it. Idempotent.

    Chains to whatever ``sys.excepthook`` was installed before this call
    (not ``sys.__excepthook__``), so a third-party hook already in place
    -- pytest, IPython, an APM agent -- keeps running instead of being
    silently dropped.
    """
    global _installed
    if _installed:
        return
    _installed = True

    previous = sys.excepthook

    def _hook(exc_type, exc, tb):
        previous(exc_type, exc, tb)
        diag = getattr(exc, "diagnosis", None)
        if diag is not None:
            print(render(diag), file=sys.stderr)

    sys.excepthook = _hook