|
26 | 26 | logger = get_logger(__name__) |
27 | 27 |
|
28 | 28 |
|
| 29 | +def _clean_ansi_codes(text: str) -> str: |
| 30 | + """Remove ANSI escape sequences (color codes, etc.)""" |
| 31 | + import re |
| 32 | + |
| 33 | + ansi_escape = re.compile(r"\x1b\[[0-9;]*m") |
| 34 | + return ansi_escape.sub("", text) |
| 35 | + |
| 36 | + |
| 37 | +def _format_execution_result(result_str: str) -> str: |
| 38 | + """Format the execution results, handle escape characters and JSON structures""" |
| 39 | + try: |
| 40 | + result_json = json.loads(result_str) |
| 41 | + |
| 42 | + if not result_json.get("success"): |
| 43 | + message = result_json.get("message", "Unknown error") |
| 44 | + outputs = result_json.get("data", {}).get("outputs", []) |
| 45 | + if outputs and isinstance(outputs[0], dict): |
| 46 | + error_msg = outputs[0].get("ename", "Unknown error") |
| 47 | + return f"Execution failed: {message}, {error_msg}" |
| 48 | + |
| 49 | + outputs = result_json.get("data", {}).get("outputs", []) |
| 50 | + if not outputs: |
| 51 | + return "No output generated" |
| 52 | + |
| 53 | + formatted_lines = [] |
| 54 | + for output in outputs: |
| 55 | + if output and isinstance(output, dict) and "text" in output: |
| 56 | + text = output["text"] |
| 57 | + text = _clean_ansi_codes(text) |
| 58 | + text = text.replace("\\n", "\n") |
| 59 | + formatted_lines.append(text) |
| 60 | + |
| 61 | + return "".join(formatted_lines).strip() |
| 62 | + |
| 63 | + except json.JSONDecodeError: |
| 64 | + return _clean_ansi_codes(result_str) |
| 65 | + except Exception as e: |
| 66 | + logger.warning(f"Error formatting result: {e}, returning raw result") |
| 67 | + return result_str |
| 68 | + |
| 69 | + |
29 | 70 | def execute_skills( |
30 | 71 | workflow_prompt: str, |
31 | 72 | skills: Optional[List[str]] = None, |
@@ -159,7 +200,7 @@ def execute_skills( |
159 | 200 | logger.debug(f"Invoke run code response: {res}") |
160 | 201 |
|
161 | 202 | try: |
162 | | - return res["Result"]["Result"] |
| 203 | + return _format_execution_result(res["Result"]["Result"]) |
163 | 204 | except KeyError as e: |
164 | 205 | logger.error(f"Error occurred while running code: {e}, response is {res}") |
165 | 206 | return res |
0 commit comments