Skip to content

Commit b0bda1e

Browse files
author
luk384090-cloud
committed
refactor(dashscope): Refactor assistant API import mechanism to support lazy loading
1 parent 11a2566 commit b0bda1e

2 files changed

Lines changed: 161 additions & 17 deletions

File tree

‎dashscope/__init__.py‎

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
# -*- coding: utf-8 -*-
22
# Copyright (c) Alibaba, Inc. and its affiliates.
3-
# pylint: disable=wrong-import-position
3+
# pylint: disable=wrong-import-position,undefined-all-variable
44

5+
import importlib
56
import logging
67
import warnings
78
from logging import NullHandler
@@ -60,22 +61,6 @@
6061
from dashscope.models import Models
6162
from dashscope.nlp.understanding import Understanding
6263
from dashscope.rerank import AioTextReRank, TextReRank
63-
from dashscope.assistants import Assistant, AssistantList, Assistants
64-
from dashscope.assistants.assistant_types import AssistantFile, DeleteResponse
65-
from dashscope.threads import (
66-
MessageFile,
67-
Messages,
68-
Run,
69-
RunList,
70-
Runs,
71-
RunStep,
72-
RunStepList,
73-
Steps,
74-
Thread,
75-
ThreadMessage,
76-
ThreadMessageList,
77-
Threads,
78-
)
7964
from dashscope.tokenizers import (
8065
Tokenization,
8166
Tokenizer,
@@ -127,6 +112,46 @@ def set_region(region: str, workspace_id: str = None):
127112
base_websocket_api_url = f"wss://{host}/api-ws/v1/inference"
128113

129114

115+
# The Assistants API (dashscope.assistants / dashscope.threads) is deprecated.
116+
# Resolve its names lazily (PEP 562) so a plain `import dashscope` does not emit
117+
# the DeprecationWarning for code that never touches them; accessing any of these
118+
# names imports dashscope.assistants, which warns once.
119+
_DEPRECATED_LAZY_IMPORTS = {
120+
"Assistant": "dashscope.assistants",
121+
"AssistantList": "dashscope.assistants",
122+
"Assistants": "dashscope.assistants",
123+
"AssistantFile": "dashscope.assistants",
124+
"DeleteResponse": "dashscope.assistants",
125+
"MessageFile": "dashscope.threads",
126+
"Messages": "dashscope.threads",
127+
"Run": "dashscope.threads",
128+
"RunList": "dashscope.threads",
129+
"Runs": "dashscope.threads",
130+
"RunStep": "dashscope.threads",
131+
"RunStepList": "dashscope.threads",
132+
"Steps": "dashscope.threads",
133+
"Thread": "dashscope.threads",
134+
"ThreadMessage": "dashscope.threads",
135+
"ThreadMessageList": "dashscope.threads",
136+
"Threads": "dashscope.threads",
137+
}
138+
139+
140+
def __getattr__(name):
141+
module_name = _DEPRECATED_LAZY_IMPORTS.get(name)
142+
if module_name is None:
143+
raise AttributeError(
144+
f"module {__name__!r} has no attribute {name!r}",
145+
)
146+
value = getattr(importlib.import_module(module_name), name)
147+
globals()[name] = value
148+
return value
149+
150+
151+
def __dir__():
152+
return sorted(set(globals()) | set(_DEPRECATED_LAZY_IMPORTS))
153+
154+
130155
__all__ = [
131156
"__version__",
132157
"base_compatible_api_url",
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# -*- coding: utf-8 -*-
2+
# Copyright (c) Alibaba, Inc. and its affiliates.
3+
"""Regression tests for issue #207.
4+
5+
The deprecated Assistants API must not emit a DeprecationWarning on a plain
6+
``import dashscope``; it should warn only when a deprecated name is actually
7+
accessed. These run in subprocesses so each starts from a clean import state.
8+
"""
9+
10+
import os
11+
import subprocess
12+
import sys
13+
import textwrap
14+
from pathlib import Path
15+
16+
REPO_ROOT = Path(__file__).resolve().parents[2]
17+
18+
19+
def _run(snippet, *, error_on_deprecation):
20+
env = dict(os.environ)
21+
existing = env.get("PYTHONPATH")
22+
env["PYTHONPATH"] = str(REPO_ROOT) + (
23+
os.pathsep + existing if existing else ""
24+
)
25+
args = [sys.executable]
26+
if error_on_deprecation:
27+
args += ["-W", "error::DeprecationWarning"]
28+
args += ["-c", textwrap.dedent(snippet)]
29+
return subprocess.run(
30+
args,
31+
capture_output=True,
32+
text=True,
33+
cwd=str(REPO_ROOT),
34+
env=env,
35+
check=False,
36+
)
37+
38+
39+
def test_plain_import_emits_no_deprecation_warning():
40+
result = _run("import dashscope", error_on_deprecation=True)
41+
assert result.returncode == 0, result.stderr
42+
43+
44+
def test_non_assistants_usage_emits_no_deprecation_warning():
45+
result = _run(
46+
"import dashscope; dashscope.Generation; dashscope.TextEmbedding",
47+
error_on_deprecation=True,
48+
)
49+
assert result.returncode == 0, result.stderr
50+
51+
52+
def test_accessing_assistants_emits_deprecation_warning():
53+
result = _run(
54+
"import dashscope; dashscope.Assistants",
55+
error_on_deprecation=True,
56+
)
57+
assert result.returncode != 0
58+
assert "DeprecationWarning" in result.stderr
59+
assert "Assistants API" in result.stderr
60+
61+
62+
def test_from_import_assistants_emits_deprecation_warning():
63+
result = _run(
64+
"from dashscope import Assistants",
65+
error_on_deprecation=True,
66+
)
67+
assert result.returncode != 0
68+
assert "DeprecationWarning" in result.stderr
69+
70+
71+
def test_accessing_threads_emits_deprecation_warning():
72+
result = _run(
73+
"import dashscope; dashscope.Threads",
74+
error_on_deprecation=True,
75+
)
76+
assert result.returncode != 0
77+
assert "DeprecationWarning" in result.stderr
78+
79+
80+
def test_direct_assistants_import_emits_deprecation_warning():
81+
result = _run("import dashscope.assistants", error_on_deprecation=True)
82+
assert result.returncode != 0
83+
assert "DeprecationWarning" in result.stderr
84+
85+
86+
def test_lazy_names_resolve_to_real_objects():
87+
import dashscope
88+
from dashscope.assistants import Assistant, Assistants
89+
from dashscope.assistants.assistant_types import (
90+
AssistantFile,
91+
DeleteResponse,
92+
)
93+
from dashscope.threads import RunStepList, Threads
94+
95+
assert dashscope.Assistants is Assistants
96+
assert dashscope.Assistant is Assistant
97+
assert dashscope.AssistantFile is AssistantFile
98+
assert dashscope.DeleteResponse is DeleteResponse
99+
assert dashscope.Threads is Threads
100+
assert dashscope.RunStepList is RunStepList
101+
102+
103+
def test_dir_includes_lazy_names():
104+
import dashscope
105+
106+
listing = dir(dashscope)
107+
for name in ("Assistants", "Threads", "Runs", "Messages"):
108+
assert name in listing
109+
110+
111+
def test_unknown_attribute_raises_attribute_error():
112+
import dashscope
113+
114+
try:
115+
dashscope.ThisNameDoesNotExist
116+
except AttributeError:
117+
pass
118+
else: # pragma: no cover
119+
raise AssertionError("expected AttributeError")

0 commit comments

Comments
 (0)