Skip to content

Commit 70cf5ec

Browse files
author
zhansheng.lzs
committed
apt: fix dict, list
1 parent 2a6b11d commit 70cf5ec

17 files changed

Lines changed: 86 additions & 70 deletions

File tree

dashscope/finetune/reinforcement/common/cli.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,14 @@ def format_output(data: Any, fmt: str = "table") -> None:
4444
console.print(
4545
yaml.dump(data, default_flow_style=False, allow_unicode=True))
4646
else:
47-
if isinstance(data, dict):
47+
if isinstance(data, Dict):
4848
table = Table(title="Result", show_header=True,
4949
header_style="bold cyan")
5050
table.add_column("Key", style="cyan")
5151
table.add_column("Value", style="green")
5252
for k, v in data.items():
5353
val = str(v) if not isinstance(v,
54-
(dict, list)) else json.dumps(v,
54+
(Dict, list)) else json.dumps(v,
5555
ensure_ascii=False,
5656
indent=2)
5757
table.add_row(str(k), val)
@@ -180,12 +180,12 @@ async def _test_fc_async(
180180
func_type: str,
181181
input_data: Dict[str, Any],
182182
api_key: Optional[str]
183-
) -> dict:
183+
) -> Dict:
184184
"""Core asynchronous testing logic."""
185185
try:
186186
result = await AgenticRL.test_functions(
187187
instance_id=instance_id,
188-
type=func_type,
188+
function_type=func_type,
189189
input_data=input_data,
190190
api_key=api_key,
191191
)

dashscope/finetune/reinforcement/common/errors.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"""
44

55
from datetime import datetime
6-
from typing import Optional
6+
from typing import Optional, Dict
77

88

99
class AgenticRLError(Exception):
@@ -67,7 +67,7 @@ class OutputError(AgenticRLError):
6767
"""Raised when service response fails output validation checks"""
6868

6969
def __init__(self, message: str, error_code: int = 1200,
70-
response: Optional[dict] = None):
70+
response: Optional[Dict] = None):
7171
super().__init__(message, error_code)
7272
self.response = response
7373

@@ -177,8 +177,8 @@ class ValidationError(AgenticRLError):
177177
"""Base class for data validation failures"""
178178

179179
def __init__(self, message: str, error_code: int = 1500,
180-
invalid_data: Optional[dict] = None,
181-
validation_rules: Optional[dict] = None):
180+
invalid_data: Optional[Dict] = None,
181+
validation_rules: Optional[Dict] = None):
182182
super().__init__(f"Validation failed: {message}", error_code)
183183
self.invalid_data = invalid_data
184184
self.validation_rules = validation_rules

dashscope/finetune/reinforcement/common/model.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -842,7 +842,7 @@ async def verify_function(
842842
instance_id: Optional[str] = None,
843843
instance_url: Optional[str] = None,
844844
instance_token: Optional[str] = None
845-
) -> dict:
845+
) -> Dict:
846846
"""Validate deployed function functionality."""
847847
try:
848848
# Get instance metadata
@@ -884,6 +884,17 @@ async def verify_function(
884884
raise ValidationError("Unsupported input type",
885885
error_code=2402)
886886

887+
except Exception as e:
888+
logger.error(
889+
f"Validation failed | Instance: {instance_id}, "
890+
f"Error: {str(e)}",
891+
exc_info=True
892+
)
893+
raise ValidationError(
894+
f"Function verification failed: {str(e)}", error_code=2403
895+
) from e
896+
897+
try:
887898
validated = validator.model_validate(response)
888899

889900
logger.info(
@@ -901,7 +912,8 @@ async def verify_function(
901912
exc_info=True
902913
)
903914
raise ValidationError(
904-
f"Function verification failed: {str(e)}", error_code=2403
915+
f"Function verification failed: "
916+
f"{str(e)}, response: {response}", error_code=2404
905917
) from e
906918

907919

@@ -1188,7 +1200,7 @@ def combine_ids_runtimes(
11881200
if function_runtimes and i <= len(function_runtimes) - 1:
11891201
runtime_config = function_runtimes[i].copy()
11901202
if 'env' in runtime_config and isinstance(
1191-
runtime_config['env'], dict):
1203+
runtime_config['env'], Dict):
11921204
for key, value in runtime_config['env'].items():
11931205
if isinstance(value, bool):
11941206
runtime_config['env'][key] = str(value).lower()

dashscope/finetune/reinforcement/common/utils.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,10 @@ async def _handle_response(response) -> Dict[str, Any]:
100100
async def client_fc(
101101
api_key: str,
102102
url: str,
103-
input: dict,
103+
input: Dict,
104104
method: str = 'POST',
105105
content_type: str = 'application/json'
106-
) -> dict:
106+
) -> Dict:
107107
"""Client function for Function Compute API requests."""
108108
return await async_http_request(
109109
method=method,
@@ -581,9 +581,9 @@ def deep_mask(data: Any) -> Any:
581581
try:
582582
data = data.model_dump(mode='json')
583583
except AttributeError:
584-
data = data.dict()
584+
data = data.Dict()
585585

586-
if isinstance(data, dict):
586+
if isinstance(data, Dict):
587587
return {
588588
key: secret_part_str(
589589
val) if key.lower() in LOGGER_FILTER_FIELDS else deep_mask(val)
@@ -686,8 +686,8 @@ def get_func_type_id(func_type: FunctionType):
686686

687687
def deep_remove_none(obj):
688688
"""Recursively remove items with value None from dicts and lists (including nested structures)"""
689-
if isinstance(obj, dict):
690-
# Process dict: filter keys with non-None values and recursively process values
689+
if isinstance(obj, Dict):
690+
# Process Dict: filter keys with non-None values and recursively process values
691691
return {
692692
k: deep_remove_none(v)
693693
for k, v in obj.items()
@@ -843,7 +843,7 @@ def serialize_for_output(data: Any) -> Any:
843843
This function recursively processes data to ensure it can be serialized to formats like JSON.
844844
It handles:
845845
- Pydantic V2 models using model_dump()
846-
- Pydantic V1 models using dict()
846+
- Pydantic V1 models using Dict()
847847
- Regular objects via their __dict__ attribute
848848
- Lists, tuples, and dictionaries recursively
849849
- Other basic types as-is
@@ -852,20 +852,20 @@ def serialize_for_output(data: Any) -> Any:
852852
data: Input data to serialize (any type)
853853
854854
Returns:
855-
Serialized data in a format suitable for output (dict, list, or primitive)
855+
Serialized data in a format suitable for output (Dict, list, or primitive)
856856
"""
857857
# Handle Pydantic models (version detection)
858858
if hasattr(data, "model_dump"): # Pydantic V2
859859
return data.model_dump()
860860
elif hasattr(data, "dict"): # Pydantic V1
861-
return data.dict()
861+
return data.Dict()
862862

863863
# Handle regular objects via their attribute dictionary
864864
if hasattr(data, "__dict__"):
865865
data = data.__dict__
866866

867867
# Recursively process container types
868-
if isinstance(data, dict):
868+
if isinstance(data, Dict):
869869
return {k: serialize_for_output(v) for k, v in data.items()}
870870
elif isinstance(data, (list, tuple, set)):
871871
return [serialize_for_output(item) for item in data]

dashscope/finetune/reinforcement/component/func_decorator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def decorator(cls: Type) -> Type:
8282

8383
async def process(self, input_data: RewardInput) -> RewardOutput:
8484
"""Processes input by executing all sub-reward functions and aggregating results"""
85-
sub_rewards: dict[str, RewardOutput] = {}
85+
sub_rewards: Dict[str, RewardOutput] = {}
8686

8787
tasks = []
8888
for name, sub_func in self._reward_meta.sub_functions.items():

dashscope/finetune/reinforcement/component/observability/genai/_core.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,10 +120,10 @@ def _inner(x: Any, depth: int) -> Any:
120120
pass
121121
if hasattr(x, "dict") and callable(getattr(x, "dict", None)):
122122
try:
123-
return _inner(x.dict(), depth + 1) # type: ignore[call-arg]
123+
return _inner(x.Dict(), depth + 1) # type: ignore[call-arg]
124124
except Exception:
125125
pass
126-
if isinstance(x, dict):
126+
if isinstance(x, Dict):
127127
out: Dict[str, Any] = {}
128128
for i, (k, v) in enumerate(x.items()):
129129
if i >= limits.max_items:

dashscope/finetune/reinforcement/component/observability/genai/messages.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def unwrap_openai_completion(completion: Any) -> Any:
125125
try:
126126
if completion is None:
127127
return None
128-
if isinstance(completion, dict):
128+
if isinstance(completion, Dict):
129129
return completion
130130
if getattr(completion, "choices", None) is not None:
131131
return completion
@@ -146,15 +146,15 @@ def _shape_args_for_debug(arguments: Any) -> Dict[str, Any]:
146146
return {"args_type": "None", "args_str_len": 0}
147147
if isinstance(arguments, str):
148148
return {"args_type": "str", "args_str_len": len(arguments)}
149-
if isinstance(arguments, (dict, list)):
149+
if isinstance(arguments, (Dict, list)):
150150
return {"args_type": type(arguments).__name__,
151151
"args_json_len": len(json.dumps(arguments, default=str))}
152152
return {"args_type": type(arguments).__name__,
153153
"args_repr_len": len(repr(arguments))}
154154

155155

156156
def _first_tool_call_keys(tc: Any) -> Any:
157-
if isinstance(tc, dict):
157+
if isinstance(tc, Dict):
158158
return sorted(tc.keys())
159159
out = []
160160
for k in ("function", "name", "args", "id", "type", "arguments"):
@@ -180,7 +180,7 @@ def tool_calls_to_parts(tool_calls: Any) -> List[Any]:
180180
parts: List[Any] = []
181181
for i, tc in enumerate(tool_calls):
182182
fn = getattr(tc, "function", None)
183-
if fn is None and isinstance(tc, dict):
183+
if fn is None and isinstance(tc, Dict):
184184
fn = tc.get("function")
185185
name = ""
186186
args: Any = "{}"
@@ -191,7 +191,7 @@ def tool_calls_to_parts(tool_calls: Any) -> List[Any]:
191191
# ``messages`` history). Never use ``getattr(fn, "arguments", "{}")`` for dicts:
192192
# ``getattr`` returns the default literal ``"{}"``, which is truthy and prevents
193193
# the ``or fn.get("arguments", ...)`` fallback from running — real arguments are lost.
194-
if isinstance(fn, dict):
194+
if isinstance(fn, Dict):
195195
name = fn.get("name") or ""
196196
raw_args = fn.get("arguments")
197197
else:
@@ -201,17 +201,17 @@ def tool_calls_to_parts(tool_calls: Any) -> List[Any]:
201201
else:
202202
branch = "top_level_lc"
203203
name = getattr(tc, "name", "") or (
204-
tc.get("name") if isinstance(tc, dict) else "")
204+
tc.get("name") if isinstance(tc, Dict) else "")
205205
# LangChain ``ToolCall`` / LC-like dicts: payload lives in top-level ``args``, not
206206
# OpenAI's nested ``function.arguments`` string.
207-
if isinstance(tc, dict):
207+
if isinstance(tc, Dict):
208208
if tc.get("args") is not None:
209209
args = tc["args"]
210210
else:
211211
lc_args = getattr(tc, "args", None)
212212
if lc_args is not None:
213213
args = lc_args
214-
tid = getattr(tc, "id", None) if not isinstance(tc, dict) else tc.get(
214+
tid = getattr(tc, "id", None) if not isinstance(tc, Dict) else tc.get(
215215
"id")
216216
args_str = _sanitize_tool_call_arguments(args)
217217
if _debug_llm_tool_calls():
@@ -220,7 +220,7 @@ def tool_calls_to_parts(tool_calls: Any) -> List[Any]:
220220
if fn is not None:
221221
raw_a = (
222222
fn.get("arguments", "__sentinel__")
223-
if isinstance(fn, dict)
223+
if isinstance(fn, Dict)
224224
else getattr(fn, "arguments", "__sentinel__")
225225
)
226226
nested_fn_diag = {
@@ -262,7 +262,7 @@ def _extract_tool_calls_from_message_obj(m: Any) -> Any:
262262
if tc is not None:
263263
return tc
264264
ak = getattr(m, "additional_kwargs", None)
265-
if isinstance(ak, dict):
265+
if isinstance(ak, Dict):
266266
return ak.get("tool_calls")
267267
return None
268268

@@ -307,7 +307,7 @@ def openai_chat_messages_to_input_messages(messages: Any) -> List[Any]:
307307
_debug_llm_tool_calls_log_exc()
308308
out: List[Any] = []
309309
for idx, m in enumerate(messages):
310-
if isinstance(m, dict):
310+
if isinstance(m, Dict):
311311
raw_role = m.get("role")
312312
content = m.get("content")
313313
tool_calls = m.get("tool_calls")
@@ -392,29 +392,29 @@ def openai_completion_to_output_messages(completion: Any) -> List[Any]:
392392

393393
# OpenAI-compatible SDKs sometimes return plain dicts (e.g. http clients or
394394
# wrappers). Handle both object- and dict-shaped responses.
395-
if isinstance(completion, dict):
395+
if isinstance(completion, Dict):
396396
choices = completion.get("choices") or []
397397
else:
398398
choices = getattr(completion, "choices", None) or []
399399
if not choices:
400400
return []
401401
result: List[Any] = []
402402
for ch in choices:
403-
if isinstance(ch, dict):
403+
if isinstance(ch, Dict):
404404
msg = ch.get("message")
405405
finish = ch.get("finish_reason") or "stop"
406406
else:
407407
msg = getattr(ch, "message", None)
408408
finish = getattr(ch, "finish_reason", None) or "stop"
409409

410-
if isinstance(msg, dict):
410+
if isinstance(msg, Dict):
411411
role = msg.get("role") or "assistant"
412412
else:
413413
role = getattr(msg, "role",
414414
"assistant") if msg is not None else "assistant"
415415
parts: List[Any] = []
416416
if msg is not None:
417-
if isinstance(msg, dict):
417+
if isinstance(msg, Dict):
418418
content = msg.get("content")
419419
else:
420420
content = getattr(msg, "content", None)
@@ -423,7 +423,7 @@ def openai_completion_to_output_messages(completion: Any) -> List[Any]:
423423
Text(content=content if isinstance(content, str) else str(
424424
content))
425425
)
426-
if isinstance(msg, dict):
426+
if isinstance(msg, Dict):
427427
tool_calls = msg.get("tool_calls")
428428
else:
429429
tool_calls = getattr(msg, "tool_calls", None)
@@ -452,7 +452,7 @@ def dashscope_response_to_output_messages(response: Any) -> List[Any]:
452452
role = "assistant"
453453
parts: List[Any] = []
454454
if msg is not None:
455-
if isinstance(msg, dict):
455+
if isinstance(msg, Dict):
456456
role = msg.get("role") or "assistant"
457457
content = msg.get("content")
458458
tool_calls = msg.get("tool_calls")

0 commit comments

Comments
 (0)