Skip to content

Commit 72fe6aa

Browse files
authored
feat: support Ark context management and reliable inline-image tracing (#667)
* feat: support Ark responses context management * fix(observability): harden inline image TOS upload * feat(model): support fallbacks for Ark Responses API
1 parent 4959baa commit 72fe6aa

11 files changed

Lines changed: 490 additions & 64 deletions

File tree

‎docs/content/docs/framework/agent/responses-api.en.mdx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ root_agent = Agent(
4141
)
4242
```
4343

44+
**Model fallbacks**
45+
46+
The Responses API also accepts a `model_name` list for resilience. If a request fails, VeADK tries each subsequent model in order until one succeeds or all models fail.
47+
48+
```python
49+
root_agent = Agent(
50+
enable_responses=True,
51+
model_name=["doubao-seed-1-8-251228", "deepseek-r1-250528"],
52+
)
53+
```
54+
4455
**Result**
4556

4657
![responses-api](/assets/images/agents/responses_api.png)

‎docs/content/docs/framework/agent/responses-api.mdx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ root_agent = Agent(
4141
)
4242
```
4343

44+
**多模型容错**
45+
46+
Responses API 同样支持通过 `model_name` 列表配置容错模型。请求失败时会按顺序尝试后续模型,直到成功或所有模型均失败。
47+
48+
```python
49+
root_agent = Agent(
50+
enable_responses=True,
51+
model_name=["doubao-seed-1-8-251228", "deepseek-r1-250528"],
52+
)
53+
```
54+
4455
**效果展示**
4556

4657
![responses-api](/assets/images/agents/responses_api.png)

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ dependencies = [
2929
"opentelemetry-exporter-otlp==1.37.0",
3030
"opentelemetry-instrumentation-logging>=0.56b0",
3131
"wrapt==1.17.2", # For patching built-in functions
32-
"volcengine-python-sdk>=5.0.1", # For Volcengine API
32+
"volcengine-python-sdk>=5.0.36", # For Volcengine API and Ark Responses context management
3333
"volcengine>=1.0.193", # For Volcengine sign and AgentKit Runtime API access
3434
"agent-pilot-sdk==0.1.2", # Prompt optimization by Volcengine AgentPilot/PromptPilot toolkits
3535
"fastmcp>=2.12.3", # For running MCP
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
from veadk.models.ark_llm import request_reorganization_by_ark
16+
17+
18+
def test_request_reorganization_preserves_context_management():
19+
context_management = {
20+
"edits": [
21+
{
22+
"type": "clear_thinking",
23+
"keep": {"type": "thinking_turns", "value": 1},
24+
},
25+
{
26+
"type": "clear_tool_uses",
27+
"trigger": {"type": "tool_uses", "value": 30},
28+
"keep": {"type": "tool_uses", "value": 20},
29+
},
30+
]
31+
}
32+
33+
request = request_reorganization_by_ark(
34+
{
35+
"model": "openai/test-model",
36+
"input": [],
37+
"context_management": context_management,
38+
}
39+
)
40+
41+
assert request["context_management"] == context_management
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
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 httpx
16+
import pytest
17+
from google.adk.models import LlmResponse
18+
from volcenginesdkarkruntime._exceptions import ArkBadRequestError
19+
20+
from veadk.models.ark_llm import ArkLlm
21+
22+
23+
@pytest.mark.asyncio
24+
async def test_ark_llm_uses_next_model_when_primary_fails(monkeypatch):
25+
model = ArkLlm(
26+
model="openai/primary-model",
27+
fallbacks=["openai/fallback-model"],
28+
)
29+
calls = []
30+
31+
async def fake_generate(self, responses_args, stream=False):
32+
calls.append((responses_args["model"], stream))
33+
if responses_args["model"] == "openai/primary-model":
34+
raise RuntimeError("primary failed")
35+
yield LlmResponse(model_version=responses_args["model"])
36+
37+
monkeypatch.setattr(ArkLlm, "generate_content_via_responses", fake_generate)
38+
39+
responses = [
40+
response
41+
async for response in model._generate_content_with_fallbacks(
42+
{"input": []}, stream=True
43+
)
44+
]
45+
46+
assert calls == [
47+
("openai/primary-model", True),
48+
("openai/fallback-model", True),
49+
]
50+
assert [response.model_version for response in responses] == [
51+
"openai/fallback-model"
52+
]
53+
54+
55+
@pytest.mark.asyncio
56+
async def test_ark_llm_raises_last_error_when_all_models_fail(monkeypatch):
57+
model = ArkLlm(
58+
model="openai/primary-model",
59+
fallbacks=["openai/fallback-model"],
60+
)
61+
62+
async def fake_generate(self, responses_args, stream=False):
63+
if False:
64+
yield
65+
raise RuntimeError(f"{responses_args['model']} failed")
66+
67+
monkeypatch.setattr(ArkLlm, "generate_content_via_responses", fake_generate)
68+
69+
with pytest.raises(RuntimeError, match="openai/fallback-model failed"):
70+
async for _ in model._generate_content_with_fallbacks({"input": []}):
71+
pass
72+
73+
74+
@pytest.mark.asyncio
75+
async def test_ark_llm_does_not_fallback_after_stream_output(monkeypatch):
76+
model = ArkLlm(
77+
model="openai/primary-model",
78+
fallbacks=["openai/fallback-model"],
79+
)
80+
calls = []
81+
82+
async def fake_generate(self, responses_args, stream=False):
83+
calls.append(responses_args["model"])
84+
yield LlmResponse(model_version=responses_args["model"], partial=True)
85+
raise RuntimeError("stream interrupted")
86+
87+
monkeypatch.setattr(ArkLlm, "generate_content_via_responses", fake_generate)
88+
89+
generator = model._generate_content_with_fallbacks({"input": []}, stream=True)
90+
first_response = await anext(generator)
91+
assert first_response.model_version == "openai/primary-model"
92+
93+
with pytest.raises(RuntimeError, match="stream interrupted"):
94+
await anext(generator)
95+
96+
assert calls == ["openai/primary-model"]
97+
98+
99+
@pytest.mark.asyncio
100+
async def test_ark_llm_retries_expired_response_before_fallback(monkeypatch):
101+
model = ArkLlm(
102+
model="openai/primary-model",
103+
fallbacks=["openai/fallback-model"],
104+
)
105+
calls = []
106+
request = httpx.Request("POST", "https://ark.example/v1/responses")
107+
expired_error = ArkBadRequestError(
108+
"previous response expired",
109+
response=httpx.Response(400, request=request),
110+
body={"code": "InvalidParameter.PreviousResponseNotFound"},
111+
request_id="request-id",
112+
)
113+
114+
async def fake_generate(self, responses_args, stream=False):
115+
calls.append(
116+
(responses_args["model"], responses_args.get("previous_response_id"))
117+
)
118+
if len(calls) == 1:
119+
raise expired_error
120+
if responses_args["model"] == "openai/primary-model":
121+
raise RuntimeError("primary failed without cache")
122+
yield LlmResponse(model_version=responses_args["model"])
123+
124+
monkeypatch.setattr(ArkLlm, "generate_content_via_responses", fake_generate)
125+
126+
responses = [
127+
response
128+
async for response in model._generate_content_with_fallbacks(
129+
{"input": [], "previous_response_id": "expired-id"}
130+
)
131+
]
132+
133+
assert calls == [
134+
("openai/primary-model", "expired-id"),
135+
("openai/primary-model", None),
136+
("openai/fallback-model", None),
137+
]
138+
assert responses[0].model_version == "openai/fallback-model"

‎tests/test_agent.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,46 @@ def test_agent_model_creation(mock_lite_llm):
136136
assert agent.model == mock_model
137137

138138

139+
@patch("veadk.models.ark_llm.ArkLlm")
140+
def test_agent_passes_context_management_to_responses_model(mock_ark_llm):
141+
context_management = {
142+
"edits": [
143+
{
144+
"type": "clear_thinking",
145+
"keep": {"type": "thinking_turns", "value": 1},
146+
}
147+
]
148+
}
149+
150+
Agent(
151+
model_name="test_model",
152+
model_provider="ark",
153+
model_api_key="test_key",
154+
model_api_base="test_base",
155+
enable_responses=True,
156+
model_extra_config={"context_management": context_management},
157+
)
158+
159+
assert mock_ark_llm.call_args.kwargs["context_management"] == context_management
160+
161+
162+
@patch("veadk.models.ark_llm.ArkLlm")
163+
def test_agent_configures_responses_model_fallbacks(mock_ark_llm):
164+
Agent(
165+
model_name=["primary-model", "fallback-model-1", "fallback-model-2"],
166+
model_provider="openai",
167+
model_api_key="test_key",
168+
model_api_base="test_base",
169+
enable_responses=True,
170+
)
171+
172+
assert mock_ark_llm.call_args.kwargs["model"] == "openai/primary-model"
173+
assert mock_ark_llm.call_args.kwargs["fallbacks"] == [
174+
"openai/fallback-model-1",
175+
"openai/fallback-model-2",
176+
]
177+
178+
139179
@patch.dict("os.environ", {"MODEL_AGENT_API_KEY": "mock_api_key"})
140180
def test_agent_with_existing_model():
141181
existing_model = LiteLlm(model="test_model")

0 commit comments

Comments
 (0)