Skip to content

Commit 55dc810

Browse files
authored
Merge branch 'main' into action-github
2 parents 2563912 + ed4ee28 commit 55dc810

37 files changed

+2519
-2949
lines changed

.env

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
PYTHON_KEYRING_BACKEND=keyring.backends.null.Keyring
2+
ZHIPUAI_API_KEY={YOUR API KEY}

pyproject.toml

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "zhipuai"
3-
version = "2.1.5.20250626"
3+
version = "2.1.5.20250701"
44
description = "A SDK library for accessing big model apis from ZhipuAI"
55
authors = ["Zhipu AI"]
66
readme = "README.md"
@@ -57,6 +57,13 @@ select = [
5757
"T201", # print
5858
]
5959

60+
[tool.ruff]
61+
line-length = 88
62+
63+
[tool.ruff.format]
64+
quote-style = "single"
65+
indent-style = "tab"
66+
docstring-code-format = true
6067

6168
[tool.coverage.run]
6269
omit = [

tests/conftest.py

Lines changed: 90 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -1,115 +1,111 @@
11
"""Configuration for unit tests."""
2-
import logging
2+
33
from importlib import util
44
from pathlib import Path
5-
from typing import Dict, List, Sequence
5+
from typing import Dict, Sequence
66

77
import pytest
88
from pytest import Config, Function, Parser
9+
910
from zhipuai.core.logs import (
10-
get_config_dict,
11-
get_log_file,
12-
get_timestamp_ms,
11+
get_config_dict,
12+
get_log_file,
13+
get_timestamp_ms,
1314
)
1415

1516

16-
1717
def pytest_addoption(parser: Parser) -> None:
18-
"""Add custom command line options to pytest."""
19-
parser.addoption(
20-
"--only-extended",
21-
action="store_true",
22-
help="Only run extended tests. Does not allow skipping any extended tests.",
23-
)
24-
parser.addoption(
25-
"--only-core",
26-
action="store_true",
27-
help="Only run core tests. Never runs any extended tests.",
28-
)
18+
"""Add custom command line options to pytest."""
19+
parser.addoption(
20+
'--only-extended',
21+
action='store_true',
22+
help='Only run extended tests. Does not allow skipping any extended tests.',
23+
)
24+
parser.addoption(
25+
'--only-core',
26+
action='store_true',
27+
help='Only run core tests. Never runs any extended tests.',
28+
)
2929

3030

3131
def pytest_collection_modifyitems(config: Config, items: Sequence[Function]) -> None:
32-
"""Add implementations for handling custom markers.
33-
34-
At the moment, this adds support for a custom `requires` marker.
35-
36-
The `requires` marker is used to denote tests that require one or more packages
37-
to be installed to run. If the package is not installed, the test is skipped.
38-
39-
The `requires` marker syntax is:
40-
41-
.. code-block:: python
42-
43-
@pytest.mark.requires("package1", "package2")
44-
def test_something():
45-
...
46-
"""
47-
# Mapping from the name of a package to whether it is installed or not.
48-
# Used to avoid repeated calls to `util.find_spec`
49-
required_pkgs_info: Dict[str, bool] = {}
50-
51-
only_extended = config.getoption("--only-extended") or False
52-
only_core = config.getoption("--only-core") or False
53-
54-
if only_extended and only_core:
55-
raise ValueError("Cannot specify both `--only-extended` and `--only-core`.")
56-
57-
for item in items:
58-
requires_marker = item.get_closest_marker("requires")
59-
if requires_marker is not None:
60-
if only_core:
61-
item.add_marker(pytest.mark.skip(reason="Skipping not a core test."))
62-
continue
63-
64-
# Iterate through the list of required packages
65-
required_pkgs = requires_marker.args
66-
for pkg in required_pkgs:
67-
# If we haven't yet checked whether the pkg is installed
68-
# let's check it and store the result.
69-
if pkg not in required_pkgs_info:
70-
try:
71-
installed = util.find_spec(pkg) is not None
72-
except Exception:
73-
installed = False
74-
required_pkgs_info[pkg] = installed
75-
76-
if not required_pkgs_info[pkg]:
77-
if only_extended:
78-
pytest.fail(
79-
f"Package `{pkg}` is not installed but is required for "
80-
f"extended tests. Please install the given package and "
81-
f"try again.",
82-
)
83-
84-
else:
85-
# If the package is not installed, we immediately break
86-
# and mark the test as skipped.
87-
item.add_marker(
88-
pytest.mark.skip(reason=f"Requires pkg: `{pkg}`")
89-
)
90-
break
91-
else:
92-
if only_extended:
93-
item.add_marker(
94-
pytest.mark.skip(reason="Skipping not an extended test.")
95-
)
32+
"""Add implementations for handling custom markers.
33+
34+
At the moment, this adds support for a custom `requires` marker.
35+
36+
The `requires` marker is used to denote tests that require one or more packages
37+
to be installed to run. If the package is not installed, the test is skipped.
38+
39+
The `requires` marker syntax is:
40+
41+
.. code-block:: python
42+
43+
@pytest.mark.requires('package1', 'package2')
44+
def test_something(): ...
45+
"""
46+
# Mapping from the name of a package to whether it is installed or not.
47+
# Used to avoid repeated calls to `util.find_spec`
48+
required_pkgs_info: Dict[str, bool] = {}
49+
50+
only_extended = config.getoption('--only-extended') or False
51+
only_core = config.getoption('--only-core') or False
52+
53+
if only_extended and only_core:
54+
raise ValueError('Cannot specify both `--only-extended` and `--only-core`.')
55+
56+
for item in items:
57+
requires_marker = item.get_closest_marker('requires')
58+
if requires_marker is not None:
59+
if only_core:
60+
item.add_marker(pytest.mark.skip(reason='Skipping not a core test.'))
61+
continue
62+
63+
# Iterate through the list of required packages
64+
required_pkgs = requires_marker.args
65+
for pkg in required_pkgs:
66+
# If we haven't yet checked whether the pkg is installed
67+
# let's check it and store the result.
68+
if pkg not in required_pkgs_info:
69+
try:
70+
installed = util.find_spec(pkg) is not None
71+
except Exception:
72+
installed = False
73+
required_pkgs_info[pkg] = installed
74+
75+
if not required_pkgs_info[pkg]:
76+
if only_extended:
77+
pytest.fail(
78+
f'Package `{pkg}` is not installed but is required for '
79+
f'extended tests. Please install the given package and '
80+
f'try again.',
81+
)
82+
83+
else:
84+
# If the package is not installed, we immediately break
85+
# and mark the test as skipped.
86+
item.add_marker(pytest.mark.skip(reason=f'Requires pkg: `{pkg}`'))
87+
break
88+
else:
89+
if only_extended:
90+
item.add_marker(pytest.mark.skip(reason='Skipping not an extended test.'))
9691

9792

9893
@pytest.fixture
9994
def logging_conf() -> dict:
100-
return get_config_dict(
101-
"info",
102-
get_log_file(log_path="logs", sub_dir=f"local_{get_timestamp_ms()}"),
103-
1024*1024,
104-
1024*1024*1024,
105-
)
95+
return get_config_dict(
96+
'info',
97+
get_log_file(log_path='logs', sub_dir=f'local_{get_timestamp_ms()}'),
98+
1024 * 1024,
99+
1024 * 1024 * 1024,
100+
)
101+
106102

107103
@pytest.fixture
108104
def test_file_path(request) -> Path:
109-
from pathlib import Path
110-
import os
111-
# 当前执行目录
112-
# 获取当前测试文件的路径
113-
test_file_path = Path(str(request.fspath)).parent
114-
print("test_file_path:",test_file_path)
115-
return test_file_path
105+
from pathlib import Path
106+
107+
# 当前执行目录
108+
# 获取当前测试文件的路径
109+
test_file_path = Path(str(request.fspath)).parent
110+
print('test_file_path:', test_file_path)
111+
return test_file_path

tests/integration_tests/speech.wav

104 KB
Binary file not shown.

tests/integration_tests/test.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
11
import time
22

33
from zhipuai import ZhipuAI
4+
45
client = ZhipuAI() # 填写您自己的APIKey
56

67
response = client.videos.generations(
7-
model="cogvideo",
8-
prompt="一个年轻的艺术家在一片彩虹上用调色板作画。"
9-
# prompt="一只卡通狐狸在森林里跳着欢快的爵士舞。"
10-
# prompt="这是一部汽车广告片,描述了一位30岁的汽车赛车手戴着红色头盔的赛车冒险。背景是蔚蓝的天空和苛刻的沙漠环境,电影风格使用35毫米胶片拍摄,色彩鲜艳夺目。"
8+
model='cogvideo',
9+
prompt='一个年轻的艺术家在一片彩虹上用调色板作画。',
10+
# prompt="一只卡通狐狸在森林里跳着欢快的爵士舞。"
11+
# prompt="这是一部汽车广告片,描述了一位30岁的汽车赛车手戴着红色头盔的赛车冒险。背景是蔚蓝的天空和苛刻的沙漠环境,电影风格使用35毫米胶片拍摄,色彩鲜艳夺目。"
1112
)
1213
print(response)
1314
task_id = response.id
1415
task_status = response.task_status
1516
get_cnt = 0
1617

1718
while task_status == 'PROCESSING' and get_cnt <= 40:
18-
result_response = client.videos.retrieve_videos_result(
19-
id=task_id
20-
)
21-
print(result_response)
22-
task_status = result_response.task_status
19+
result_response = client.videos.retrieve_videos_result(id=task_id)
20+
print(result_response)
21+
task_status = result_response.task_status
2322

24-
time.sleep(2)
25-
get_cnt += 1
23+
time.sleep(2)
24+
get_cnt += 1
Lines changed: 46 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,54 @@
1-
import os.path
2-
3-
from zhipuai import ZhipuAI
4-
import zhipuai
5-
import time
6-
71
import logging
82
import logging.config
3+
import time
4+
5+
import zhipuai
6+
from zhipuai import ZhipuAI
97

108

119
def test_completions_sync(logging_conf):
12-
logging.config.dictConfig(logging_conf) # type: ignore
13-
client = ZhipuAI() # 填写您自己的APIKey
14-
try:
15-
# 生成request_id
16-
request_id = time.time()
17-
print(f"request_id:{request_id}")
18-
response = client.agents.invoke(
19-
request_id=request_id,
20-
agent_id="general_translation",
21-
messages=[
22-
{
23-
"role": "user",
24-
"content": "tell me a joke"
25-
}
26-
],
27-
user_id="12345678"
28-
)
29-
print(response)
10+
logging.config.dictConfig(logging_conf) # type: ignore
11+
client = ZhipuAI() # 填写您自己的APIKey
12+
try:
13+
# 生成request_id
14+
request_id = time.time()
15+
print(f'request_id:{request_id}')
16+
response = client.agents.invoke(
17+
request_id=request_id,
18+
agent_id='general_translation',
19+
messages=[{'role': 'user', 'content': 'tell me a joke'}],
20+
user_id='12345678',
21+
)
22+
print(response)
23+
24+
except zhipuai.core._errors.APIRequestFailedError as err:
25+
print(err)
26+
except zhipuai.core._errors.APIInternalError as err:
27+
print(err)
28+
except zhipuai.core._errors.APIStatusError as err:
29+
print(err)
3030

31-
except zhipuai.core._errors.APIRequestFailedError as err:
32-
print(err)
33-
except zhipuai.core._errors.APIInternalError as err:
34-
print(err)
35-
except zhipuai.core._errors.APIStatusError as err:
36-
print(err)
3731

3832
def test_completions_stream(logging_conf):
39-
logging.config.dictConfig(logging_conf) # type: ignore
40-
client = ZhipuAI() # 填写您自己的APIKey
41-
try:
42-
# 生成request_id
43-
request_id = time.time()
44-
print(f"request_id:{request_id}")
45-
response = client.agents.invoke(
46-
request_id=request_id,
47-
agent_id="general_translation",
48-
messages=[
49-
{
50-
"role": "user",
51-
"content": "tell me a joke"
52-
}
53-
],
54-
user_id="12345678",
55-
stream=True
56-
)
57-
for item in response:
58-
print(item)
59-
60-
61-
except zhipuai.core._errors.APIRequestFailedError as err:
62-
print(err)
63-
except zhipuai.core._errors.APIInternalError as err:
64-
print(err)
65-
except zhipuai.core._errors.APIStatusError as err:
66-
print(err)
33+
logging.config.dictConfig(logging_conf) # type: ignore
34+
client = ZhipuAI() # 填写您自己的APIKey
35+
try:
36+
# 生成request_id
37+
request_id = time.time()
38+
print(f'request_id:{request_id}')
39+
response = client.agents.invoke(
40+
request_id=request_id,
41+
agent_id='general_translation',
42+
messages=[{'role': 'user', 'content': 'tell me a joke'}],
43+
user_id='12345678',
44+
stream=True,
45+
)
46+
for item in response:
47+
print(item)
48+
49+
except zhipuai.core._errors.APIRequestFailedError as err:
50+
print(err)
51+
except zhipuai.core._errors.APIInternalError as err:
52+
print(err)
53+
except zhipuai.core._errors.APIStatusError as err:
54+
print(err)

0 commit comments

Comments
 (0)