Skip to content

Commit c7fd907

Browse files
committed
Merge remote-tracking branch 'upstream/main'
2 parents 5bd4a31 + f2f5279 commit c7fd907

File tree

23 files changed

+920
-216
lines changed

23 files changed

+920
-216
lines changed

.gitignore

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,4 +196,7 @@ cython_debug/
196196

197197
**/.nuxt
198198
**/.data
199-
**./output
199+
**./output
200+
201+
*.mp3
202+
*.pcm

config.yaml.full

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,11 @@ tool:
4646
web_scraper:
4747
endpoint:
4848
api_key: # `token`
49+
# [optional] https://console.volcengine.com/speech/new/experience/tts
50+
text_to_speech:
51+
app_id: # `app_id`
52+
api_key: # `app_secret`
53+
speaker: # `speaker`
4954
# [optional] https://open.larkoffice.com/app
5055
lark:
5156
endpoint: # `app_id`

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "veadk-python"
3-
version = "0.2.21"
3+
version = "0.2.22"
44
description = "Volcengine agent development kit, integrations with Volcengine cloud services."
55
readme = "README.md"
66
requires-python = ">=3.10"
@@ -54,6 +54,7 @@ database = [
5454
"tos>=2.8.4", # For TOS storage and Viking DB
5555
"mem0ai==0.1.118", # For mem0
5656
]
57+
speech = []
5758
eval = [
5859
"prometheus-client>=0.22.1", # For exporting data to Prometheus pushgateway
5960
"deepeval>=3.2.6", # For DeepEval-based evaluation
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import pytest
16+
from unittest.mock import patch, MagicMock
17+
from veadk.auth.veauth.speech_veauth import get_speech_token
18+
19+
20+
# Test cases
21+
22+
23+
def test_get_speech_token_with_env_vars(monkeypatch):
24+
"""Test when credentials are available in environment variables"""
25+
# Setup
26+
monkeypatch.setenv("VOLCENGINE_ACCESS_KEY", "test_access_key")
27+
monkeypatch.setenv("VOLCENGINE_SECRET_KEY", "test_secret_key")
28+
29+
mock_response = {"Result": {"APIKeys": [{"APIKey": "test_api_key"}]}}
30+
31+
with patch("veadk.auth.veauth.speech_veauth.ve_request") as mock_ve_request:
32+
mock_ve_request.return_value = mock_response
33+
34+
# Execute
35+
result = get_speech_token()
36+
37+
# Verify
38+
assert result == "test_api_key"
39+
mock_ve_request.assert_called_once_with(
40+
request_body={
41+
"ProjectName": "default",
42+
"OnlyAvailable": True,
43+
},
44+
header={"X-Security-Token": ""},
45+
action="ListAPIKeys",
46+
ak="test_access_key",
47+
sk="test_secret_key",
48+
service="speech_saas_prod",
49+
version="2025-05-20",
50+
region="cn-beijing",
51+
host="open.volcengineapi.com",
52+
)
53+
54+
55+
def test_get_speech_token_with_vefaas_iam(monkeypatch):
56+
"""Test when credentials are obtained from vefaas iam"""
57+
# Setup
58+
monkeypatch.delenv("VOLCENGINE_ACCESS_KEY", raising=False)
59+
monkeypatch.delenv("VOLCENGINE_SECRET_KEY", raising=False)
60+
61+
mock_cred = MagicMock()
62+
mock_cred.access_key_id = "vefaas_access_key"
63+
mock_cred.secret_access_key = "vefaas_secret_key"
64+
mock_cred.session_token = "vefaas_session_token"
65+
66+
mock_response = {"Result": {"APIKeys": [{"APIKey": "vefaas_api_key"}]}}
67+
68+
with (
69+
patch(
70+
"veadk.auth.veauth.speech_veauth.get_credential_from_vefaas_iam"
71+
) as mock_get_cred,
72+
patch("veadk.auth.veauth.speech_veauth.ve_request") as mock_ve_request,
73+
):
74+
mock_get_cred.return_value = mock_cred
75+
mock_ve_request.return_value = mock_response
76+
77+
# Execute
78+
result = get_speech_token(region="cn-shanghai")
79+
80+
# Verify
81+
assert result == "vefaas_api_key"
82+
mock_get_cred.assert_called_once()
83+
mock_ve_request.assert_called_once_with(
84+
request_body={
85+
"ProjectName": "default",
86+
"OnlyAvailable": True,
87+
},
88+
header={"X-Security-Token": "vefaas_session_token"},
89+
action="ListAPIKeys",
90+
ak="vefaas_access_key",
91+
sk="vefaas_secret_key",
92+
service="speech_saas_prod",
93+
version="2025-05-20",
94+
region="cn-shanghai",
95+
host="open.volcengineapi.com",
96+
)
97+
98+
99+
def test_get_speech_token_invalid_response():
100+
"""Test when API response is invalid"""
101+
# Setup
102+
monkeypatch = pytest.MonkeyPatch()
103+
monkeypatch.setenv("VOLCENGINE_ACCESS_KEY", "test_access_key")
104+
monkeypatch.setenv("VOLCENGINE_SECRET_KEY", "test_secret_key")
105+
106+
mock_response = {"Error": {"Message": "Invalid request"}}
107+
108+
with patch("veadk.auth.veauth.speech_veauth.ve_request") as mock_ve_request:
109+
mock_ve_request.return_value = mock_response
110+
111+
# Execute & Verify
112+
with pytest.raises(ValueError, match="Failed to get speech api key list"):
113+
get_speech_token()

tests/test_misc.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
import sys
17+
import types
18+
19+
from veadk.utils.misc import get_agents_dir, get_agent_dir
20+
21+
22+
class GetAgentsDirTest:
23+
def test_get_agents_dir_from_main_file(monkeypatch):
24+
"""
25+
Case 1: __main__.__file__ exists (common in CLI or uv run environments)
26+
"""
27+
fake_main = types.SimpleNamespace(__file__="/tmp/project/testapp/agent.py")
28+
monkeypatch.setitem(sys.modules, "__main__", fake_main)
29+
30+
result = get_agents_dir()
31+
assert result == "/tmp/project"
32+
result = get_agent_dir()
33+
assert result == "/tmp/project/testapp"
34+
35+
def test_get_agents_dir_from_sys_argv(monkeypatch):
36+
"""
37+
Case 2: Fallback to sys.argv[0]
38+
"""
39+
fake_main = types.SimpleNamespace()
40+
monkeypatch.setitem(sys.modules, "__main__", fake_main)
41+
monkeypatch.setattr(sys, "argv", ["/tmp/project/testapp/agent.py"])
42+
43+
result = get_agents_dir()
44+
assert result == "/tmp/project"
45+
result = get_agent_dir()
46+
assert result == "/tmp/project/testapp"
47+
48+
def test_get_agents_dir_from_cwd(monkeypatch, tmp_path):
49+
"""
50+
Case 3: Fallback to current working directory (REPL or no file context)
51+
"""
52+
fake_main = types.SimpleNamespace()
53+
monkeypatch.setitem(sys.modules, "__main__", fake_main)
54+
monkeypatch.setattr(sys, "argv", [])
55+
56+
fake_cwd = tmp_path / "some_dir"
57+
fake_cwd.mkdir()
58+
59+
monkeypatch.setattr(os, "getcwd", lambda: str(fake_cwd))
60+
result = get_agents_dir()
61+
62+
# should return the parent of fake_cwd
63+
assert result == str(tmp_path)
64+
result = get_agent_dir()
65+
assert result == str(tmp_path / "some_dir")

tests/test_runtime_data_collecting.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import json
1616
import os
17+
import uuid
1718

1819
import pytest
1920
from utils import generate_events, generate_session
@@ -25,7 +26,7 @@
2526
USER_ID = "user"
2627
SESSION_ID = "session"
2728

28-
EVAL_SET_ID = "temp_unittest"
29+
EVAL_SET_ID = "temp_unittest" + uuid.uuid4().hex
2930

3031

3132
@pytest.mark.asyncio
@@ -46,7 +47,7 @@ async def test_runtime_data_collecting():
4647
recorder = EvalSetRecorder(session_service=session_service, eval_set_id=EVAL_SET_ID)
4748
dump_path = await recorder.dump(APP_NAME, USER_ID, SESSION_ID)
4849

49-
assert dump_path == f"/tmp/{APP_NAME}/{recorder.eval_set_id}.evalset.json"
50+
# assert dump_path == f"/tmp/{APP_NAME}/{recorder.eval_set_id}.evalset.json"
5051
assert os.path.exists(dump_path) and os.path.isfile(dump_path)
5152
assert os.path.getsize(dump_path) > 0
5253

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import queue
16+
import json
17+
import base64
18+
import requests
19+
from unittest import TestCase
20+
from unittest.mock import patch, MagicMock
21+
from google.adk.tools import ToolContext
22+
from veadk.tools.builtin_tools.tts import (
23+
text_to_speech,
24+
handle_server_response,
25+
save_output_to_file,
26+
_audio_player_thread,
27+
)
28+
29+
30+
class TestTTS(TestCase):
31+
def setUp(self):
32+
self.mock_tool_context = MagicMock(spec=ToolContext)
33+
self.mock_tool_context._invocation_context = MagicMock()
34+
self.mock_tool_context._invocation_context.user_id = "test_user"
35+
36+
# Mock environment variables
37+
self.patcher_env = patch.dict(
38+
"os.environ",
39+
{
40+
"TOOL_VESPEECH_APP_ID": "test_app_id",
41+
"TOOL_VESPEECH_API_KEY": "test_api_key",
42+
"TOOL_VESPEECH_SPEAKER": "test_speaker",
43+
},
44+
)
45+
self.patcher_env.start()
46+
47+
def tearDown(self):
48+
self.patcher_env.stop()
49+
50+
@patch("requests.Session")
51+
def test_tts_success(self, mock_session):
52+
"""Test successful TTS request"""
53+
# Setup mock response
54+
mock_response = MagicMock()
55+
mock_response.headers = {"X-Tt-Logid": "test_log_id"}
56+
mock_response.iter_lines.return_value = [
57+
json.dumps({"code": 0, "data": base64.b64encode(b"audio_chunk").decode()}),
58+
json.dumps({"code": 20000000}),
59+
]
60+
mock_session.return_value.post.return_value = mock_response
61+
62+
# Call function
63+
result = text_to_speech("test text", self.mock_tool_context)
64+
65+
# Assertions
66+
self.assertIsInstance(result, dict)
67+
self.assertIn("saved_audio_path", result)
68+
mock_session.return_value.post.assert_called_once()
69+
mock_response.close.assert_called_once()
70+
71+
@patch("requests.Session")
72+
def test_tts_failure(self, mock_session):
73+
"""Test TTS request failure"""
74+
# Setup mock to raise exception
75+
mock_session.return_value.post.side_effect = (
76+
requests.exceptions.RequestException("Test error")
77+
)
78+
79+
# Call function
80+
result = text_to_speech("test text", self.mock_tool_context)
81+
82+
# Assertions
83+
self.assertIsInstance(result, dict)
84+
self.assertIn("error", result)
85+
self.assertIn("Test error", result["error"])
86+
mock_session.return_value.post.assert_called_once()
87+
88+
@patch("builtins.open")
89+
def test_handle_server_response_success(self, mock_open):
90+
"""Test successful response handling"""
91+
# Setup mock response
92+
mock_response = MagicMock()
93+
mock_response.iter_lines.return_value = [
94+
json.dumps({"code": 0, "data": base64.b64encode(b"audio_chunk").decode()}),
95+
json.dumps({"code": 20000000}),
96+
]
97+
98+
# Call function
99+
handle_server_response(mock_response, "test.pcm")
100+
101+
# Assertions
102+
mock_open.assert_called_once_with("test.pcm", "wb")
103+
104+
@patch("builtins.open")
105+
def test_save_output_to_file_success(self, mock_open):
106+
"""Test successful audio file save"""
107+
# Setup mock file handler
108+
mock_file = MagicMock()
109+
mock_open.return_value.__enter__.return_value = mock_file
110+
111+
# Call function
112+
save_output_to_file(b"audio_data", "test.pcm")
113+
114+
# Assertions
115+
mock_open.assert_called_once_with("test.pcm", "wb")
116+
mock_file.write.assert_called_once_with(b"audio_data")
117+
118+
@patch("time.sleep")
119+
def test_audio_player_thread(self, mock_sleep):
120+
"""Test audio player thread"""
121+
# Setup test data
122+
mock_queue = MagicMock()
123+
mock_queue.get.side_effect = [b"audio_data", queue.Empty]
124+
mock_stream = MagicMock()
125+
stop_event = MagicMock()
126+
stop_event.is_set.side_effect = [False, True]
127+
128+
# Call function
129+
_audio_player_thread(mock_queue, mock_stream, stop_event)
130+
131+
# Assertions
132+
mock_stream.write.assert_called_once_with(b"audio_data")
133+
mock_queue.task_done.assert_called_once()

0 commit comments

Comments
 (0)