|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +import json |
| 3 | +from typing import Any, AsyncIterator, Dict, Optional, Union |
| 4 | + |
| 5 | +from agentscope_runtime.engine.helpers.agent_api_builder import ResponseBuilder |
| 6 | +from agentscope_runtime.engine.schemas.agent_schemas import ( |
| 7 | + Content, |
| 8 | + ContentType, |
| 9 | + FunctionCall, |
| 10 | + FunctionCallOutput, |
| 11 | + Message, |
| 12 | + MessageType, |
| 13 | + Role, |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +def _try_deep_parse(val: Any) -> Any: |
| 18 | + """ |
| 19 | + Recursively parse JSON-like strings into native Python objects. |
| 20 | + """ |
| 21 | + if isinstance(val, str): |
| 22 | + content = val.strip() |
| 23 | + if (content.startswith("{") and content.endswith("}")) or ( |
| 24 | + content.startswith("[") and content.endswith("]") |
| 25 | + ): |
| 26 | + try: |
| 27 | + parsed = json.loads(content) |
| 28 | + return _try_deep_parse(parsed) |
| 29 | + except Exception: |
| 30 | + # If nested JSON parsing fails, treat it as a normal string. |
| 31 | + return val |
| 32 | + return val |
| 33 | + if isinstance(val, list): |
| 34 | + return [_try_deep_parse(i) for i in val] |
| 35 | + if isinstance(val, dict): |
| 36 | + return {k: _try_deep_parse(v) for k, v in val.items()} |
| 37 | + return val |
| 38 | + |
| 39 | + |
| 40 | +def _ensure_safe_json_string(val: Any) -> str: |
| 41 | + """ |
| 42 | + Serialize content into a valid JSON string suitable for WebUI parsing. |
| 43 | + """ |
| 44 | + parsed_val = _try_deep_parse(val) |
| 45 | + if parsed_val is None: |
| 46 | + return "{}" |
| 47 | + return json.dumps(parsed_val, ensure_ascii=False) |
| 48 | + |
| 49 | + |
| 50 | +def _extract_alias_output_obj(content_str: str) -> Any: |
| 51 | + """ |
| 52 | + Extract the `output` object from Alias nested tool-result content. |
| 53 | + """ |
| 54 | + try: |
| 55 | + data = json.loads(content_str) |
| 56 | + if isinstance(data, list) and data: |
| 57 | + return data[0].get("output") |
| 58 | + except Exception: |
| 59 | + # Best-effort parse: if the string is not a valid |
| 60 | + # JSON or doesn't follow the expected structure, |
| 61 | + # fall back to returning the original string. |
| 62 | + pass |
| 63 | + return content_str |
| 64 | + |
| 65 | + |
| 66 | +class AliasAdapterState: |
| 67 | + def __init__( |
| 68 | + self, |
| 69 | + message_builder: Any, |
| 70 | + content_builder: Any, |
| 71 | + runtime_type: str, |
| 72 | + ): |
| 73 | + self.mb = message_builder |
| 74 | + self.cb = content_builder |
| 75 | + self.runtime_type = runtime_type |
| 76 | + self.last_content = "" |
| 77 | + self.is_completed = False |
| 78 | + |
| 79 | + |
| 80 | +async def adapt_alias_message_stream( |
| 81 | + source_stream: AsyncIterator[Dict[str, Any]], |
| 82 | +) -> AsyncIterator[Union[Message, Content]]: |
| 83 | + # pylint: disable=too-many-branches, too-many-statements |
| 84 | + rb = ResponseBuilder() |
| 85 | + state_map: Dict[str, AliasAdapterState] = {} |
| 86 | + last_active_key: Optional[str] = None |
| 87 | + |
| 88 | + yield rb.created() |
| 89 | + yield rb.in_progress() |
| 90 | + |
| 91 | + async for chunk in source_stream: |
| 92 | + if not isinstance(chunk, dict) or "data" not in chunk: |
| 93 | + continue |
| 94 | + |
| 95 | + messages = chunk["data"].get("messages") or [] |
| 96 | + for item in messages: |
| 97 | + alias_id = item.get("id") |
| 98 | + inner_msg = item.get("message") or {} |
| 99 | + |
| 100 | + alias_type = inner_msg.get("type") |
| 101 | + alias_status = inner_msg.get("status") |
| 102 | + tool_call_id = inner_msg.get("tool_call_id") or alias_id |
| 103 | + |
| 104 | + if alias_type in ["thought", "sub_thought"]: |
| 105 | + runtime_type = MessageType.REASONING |
| 106 | + target_role = Role.ASSISTANT |
| 107 | + elif alias_type in ["tool_call", "tool_use"]: |
| 108 | + runtime_type = MessageType.PLUGIN_CALL |
| 109 | + target_role = Role.ASSISTANT |
| 110 | + elif alias_type == "tool_result": |
| 111 | + runtime_type = MessageType.PLUGIN_CALL_OUTPUT |
| 112 | + target_role = Role.TOOL |
| 113 | + else: |
| 114 | + runtime_type = MessageType.MESSAGE |
| 115 | + target_role = Role.ASSISTANT |
| 116 | + |
| 117 | + state_key = f"{tool_call_id}_{runtime_type}" |
| 118 | + |
| 119 | + if last_active_key and last_active_key != state_key: |
| 120 | + old_state = state_map.get(last_active_key) |
| 121 | + if old_state and not old_state.is_completed: |
| 122 | + yield old_state.cb.complete() |
| 123 | + yield old_state.mb.complete() |
| 124 | + old_state.is_completed = True |
| 125 | + |
| 126 | + last_active_key = state_key |
| 127 | + |
| 128 | + if state_key not in state_map: |
| 129 | + mb = rb.create_message_builder(role=target_role) |
| 130 | + mb.message.type = runtime_type |
| 131 | + yield mb.get_message_data() |
| 132 | + |
| 133 | + if runtime_type in [ |
| 134 | + MessageType.PLUGIN_CALL, |
| 135 | + MessageType.PLUGIN_CALL_OUTPUT, |
| 136 | + ]: |
| 137 | + c_type = ContentType.DATA |
| 138 | + else: |
| 139 | + c_type = ContentType.TEXT |
| 140 | + |
| 141 | + cb = mb.create_content_builder(content_type=c_type) |
| 142 | + state_map[state_key] = AliasAdapterState(mb, cb, runtime_type) |
| 143 | + |
| 144 | + state = state_map[state_key] |
| 145 | + |
| 146 | + if runtime_type in [MessageType.MESSAGE, MessageType.REASONING]: |
| 147 | + raw_text = str(inner_msg.get("content") or "") |
| 148 | + |
| 149 | + if alias_type == "files" and "files" in inner_msg: |
| 150 | + raw_text = "\n".join( |
| 151 | + [ |
| 152 | + f"📁 [{f['filename']}]({f['url']})" |
| 153 | + for f in inner_msg["files"] |
| 154 | + ], |
| 155 | + ) |
| 156 | + |
| 157 | + if raw_text.startswith(state.last_content): |
| 158 | + delta = raw_text[len(state.last_content) :] |
| 159 | + if delta: |
| 160 | + yield state.cb.add_text_delta(delta) |
| 161 | + state.last_content = raw_text |
| 162 | + else: |
| 163 | + yield state.cb.set_text(raw_text) |
| 164 | + state.last_content = raw_text |
| 165 | + |
| 166 | + elif runtime_type == MessageType.PLUGIN_CALL: |
| 167 | + args = inner_msg.get("arguments") or {} |
| 168 | + fc = FunctionCall( |
| 169 | + call_id=tool_call_id, |
| 170 | + name=inner_msg.get("tool_name") or "tool", |
| 171 | + arguments=_ensure_safe_json_string(args), |
| 172 | + ) |
| 173 | + yield state.cb.set_data(fc.model_dump()) |
| 174 | + |
| 175 | + elif runtime_type == MessageType.PLUGIN_CALL_OUTPUT: |
| 176 | + output_obj = _extract_alias_output_obj( |
| 177 | + inner_msg.get("content", ""), |
| 178 | + ) |
| 179 | + fco = FunctionCallOutput( |
| 180 | + call_id=tool_call_id, |
| 181 | + name=inner_msg.get("tool_name") or "tool", |
| 182 | + output=_ensure_safe_json_string(output_obj), |
| 183 | + ) |
| 184 | + yield state.cb.set_data(fco.model_dump()) |
| 185 | + |
| 186 | + if alias_status == "finished" and not state.is_completed: |
| 187 | + yield state.cb.complete() |
| 188 | + yield state.mb.complete() |
| 189 | + state.is_completed = True |
| 190 | + |
| 191 | + for state in state_map.values(): |
| 192 | + if not state.is_completed: |
| 193 | + try: |
| 194 | + yield state.cb.complete() |
| 195 | + yield state.mb.complete() |
| 196 | + state.is_completed = True |
| 197 | + except Exception: |
| 198 | + # Graceful cleanup: ignore errors during the |
| 199 | + # finalization phase to ensure the main response |
| 200 | + # stream can finish without crashing. |
| 201 | + pass |
| 202 | + |
| 203 | + yield rb.completed() |
0 commit comments