解析 AI 返回的 JSON 响应
(self, response_text: str)
| 104 | return f.read() |
| 105 | |
| 106 | def _parse_json_response(self, response_text: str) -> Dict[str, Any]: |
| 107 | """解析 AI 返回的 JSON 响应""" |
| 108 | # 尝试直接解析 |
| 109 | try: |
| 110 | return json.loads(response_text) |
| 111 | except json.JSONDecodeError: |
| 112 | pass |
| 113 | |
| 114 | # 尝试从 markdown 代码块中提取 |
| 115 | json_match = re.search(r'```(?:json)?\s*\n?([\s\S]*?)\n?```', response_text) |
| 116 | if json_match: |
| 117 | try: |
| 118 | return json.loads(json_match.group(1).strip()) |
| 119 | except json.JSONDecodeError: |
| 120 | pass |
| 121 | |
| 122 | # 尝试找到 JSON 对象的开始和结束 |
| 123 | start_idx = response_text.find('{') |
| 124 | end_idx = response_text.rfind('}') |
| 125 | if start_idx != -1 and end_idx != -1: |
| 126 | try: |
| 127 | return json.loads(response_text[start_idx:end_idx + 1]) |
| 128 | except json.JSONDecodeError: |
| 129 | pass |
| 130 | |
| 131 | logger.error(f"无法解析 JSON 响应: {response_text[:200]}...") |
| 132 | raise ValueError("AI 返回的内容格式不正确,无法解析") |
| 133 | |
| 134 | def generate_content( |
| 135 | self, |