Repository: microsoft/RD-Agent
File: rdagent/oai/backend/base.py (Python)

Code before:
                json_str = re.sub(r"\bTrue\b", "true", json_str)
                json_str = re.sub(r"\bFalse\b", "false", json_str)
                json_str = re.sub(r"\bNone\b", "null", json_str)
                return json_str

            def extract_first_json(response: str) -> str:
                """提取第一个完整的JSON对象，忽略额外内容"""
                decoder = json.JSONDecoder()
                obj, idx = decoder.raw_decode(response)
                return json.dumps(obj)  # 重新序列化为干净的JSON

            def try_parse_json(content: str) -> tuple[bool, str]:
                """
                尝试解析JSON，如果有额外数据错误则提取第一个JSON对象
                """
                try:
                    json.loads(content)
                    return True, content
                except json.decoder.JSONDecodeError as e:
                    if "Extra data" in str(e):
                        try:
                            cleaned = extract_first_json(content)
                            json.loads(cleaned)
                            return True, cleaned
                        except:
                            pass
                    return False, content

            # 保存原始响应
            original_response = all_response

            # 策略1：直接解析
            success, all_response = try_parse_json(all_response)
            if not success:
                # 策略2：从代码块提取
                match = re.search(r"```json(.*)```", original_response, re.DOTALL)
                if match:
                    json_content = match.groups()[0].strip()
                    success, all_response = try_parse_json(json_content)

                if not success:
                    # 策略3：修复Python布尔值
                    fixed_content = fix_python_booleans(all_response)
                    success, all_response = try_parse_json(fixed_content)

                    if not success:
                        # 所有策略都失败，抛出异常
                        raise json.decoder.JSONDecodeError("Failed to parse JSON after all attempts", all_response, 0)

        if json_target_type is not None:
            TypeAdapter(json_target_type).validate_json(all_response)

Review comment (suggestion):
I think we can implement it in a more elegent way 
for example 
```
for json_proc in [...]:
    try:
        all_response = json_proc(all_response)
    except json.decoder.JSONDecodeError:
         pass
else:
    raise json.decoder.JSONDecodeError
```

Code after:
                        openai_imported
                        and isinstance(e, openai.APITimeoutError)
                        or (
                            isinstance(e, openai.APIError)
                            and hasattr(e, "message")
                            and "Your resource has been temporarily blocked because we detected behavior that may violate our content policy."
                            in e.message
                        )
                    ):
                        timeout_count += 1
                        if timeout_count >= LLM_SETTINGS.timeout_fail_limit:
                            logger.warning("Timeout error, please check your network connection.")
                            raise e

                    recommended_wait_seconds = self.retry_wait_seconds
                    if openai_imported and isinstance(e, openai.RateLimitError) and hasattr(e, "message"):
                        match = re.search(r"Please retry after (\d+) seconds\.", e.message)
                        if match:
                            recommended_wait_seconds = int(match.group(1))
                    time.sleep(recommended_wait_seconds)
                    if RD_Agent_TIMER_wrapper.timer.started and not isinstance(e, json.decoder.JSONDecodeError):
                        RD_Agent_TIMER_wrapper.timer.add_duration(datetime.now() - API_start_time)
                logger.warning(str(e))
                logger.warning(f"Retrying {i+1}th time...")
        error_message = f"Failed to create chat completion after {max_retry} retries."
        raise RuntimeError(error_message)

    def _add_json_in_prompt(self, messages: list[dict[str, Any]]) -> None:
        """
        add json related content in the prompt if add_json_in_prompt is True
        """
        for message in messages[::-1]:
            message["content"] = message["content"] + "\nPlease respond in json format."
            if message["role"] == LLM_SETTINGS.system_prompt_role:
                # NOTE: assumption: systemprompt is always the first message
                break

    def _create_chat_completion_auto_continue(
        self,
        messages: list[dict[str, Any]],
        json_mode: bool = False,
        chat_cache_prefix: str = "",
        seed: Optional[int] = None,
        json_target_type: Optional[str] = None,
        add_json_in_prompt: bool = False,
        **kwargs: Any,
    ) -> str:
        """
        Call the chat completion function and automatically continue the conversation if the finish_reason is length.
        """