Skip to content

Devkit (Mock & Diagnosis)

dashscope.devkit provides two opt-in developer aids with near-zero overhead when disabled. Nothing here is imported on the production success path.

  • Dev mock — static / replay / record modes that intercept HTTP requests at the transport. HTTP only; the WebSocket transport is not covered. Activate in code with dashscope.enable_dev_mock(...) or via DASHSCOPE_DEV_MOCK=<mode>. See the table below for what each mode covers.
  • Self-diagnosis — a local, bilingual rule table that turns a failed call into structured fix guidance, surfaced on DashScopeError.diagnosis.
Mode Network Coverage
static Offline A parser smoke mock for chat / multimodal only: synthesizes a response locally to exercise protocol adapters, SSE parsing and typed models. Does not simulate tool calls, structured output or job state machines; other resources (embeddings, rerank, ...) raise DevMockMiss
replay Offline Answers from recorded real responses; a miss raises DevMockMiss and never falls through to the network
record Real requests Passes through to the real service (may incur charges) and records responses for later offline replay
WebSocket — Not covered by any mode

The root module forwards the mock switches: dashscope.enable_dev_mock, dashscope.disable_dev_mock and dashscope.dev_mock_active.

Sharing recordings

record mode writes full real responses to disk, which can contain generated content, tool-call arguments or account data. Register a redactor with set_redactor before sharing fixtures, but note: the redactor only runs on bodies that parse as a single JSON document — SSE streams and binary bodies are stored verbatim and are never redacted. Registering a redactor does not mean every fixture is scrubbed.

Dev mock switches

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

Self-diagnosis

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