Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

fix: avoid IndexError in extract_text_and_code_prompts on unclosed fence (#4147)

Amirb52445657a82
diff --git a/camel/messages/base.py b/camel/messages/base.py
index 84606b7b0..4fb88e338 100644
--- a/camel/messages/base.py
+++ b/camel/messages/base.py
@@ -297,6 +297,10 @@ class BaseMessage:
Tuple[List[TextPrompt], List[CodePrompt]]: A tuple containing a
list of text prompts and a list of code prompts extracted
from the content.
+
+ Raises:
+ ValueError: If the content contains a code fence that is opened
+ but never closed (for example, truncated model output).
"""
text_prompts: List[TextPrompt] = []
code_prompts: List[CodePrompt] = []
@@ -318,8 +322,12 @@ class BaseMessage:
code_type = lines[idx].strip()[3:].strip()
idx += 1
start_idx = idx
- while not lines[idx].lstrip().startswith("```"):
+ while idx < len(lines) and (
+ not lines[idx].lstrip().startswith("```")
+ ):
idx += 1
+ if idx >= len(lines):
+ raise ValueError("Unclosed code fence in message content")
code = "\n".join(lines[start_idx:idx]).strip()
code_prompts.append(CodePrompt(code, code_type=code_type))
diff --git a/test/messages/test_message_base.py b/test/messages/test_message_base.py
index 6b9587936..6f867fc04 100644
--- a/test/messages/test_message_base.py
+++ b/test/messages/test_message_base.py
@@ -85,6 +85,23 @@ def test_extract_text_and_code_prompts():
assert code_prompts[1].code_type == "c"
+def test_extract_text_and_code_prompts_unclosed_fence():
+ # A code block whose closing fence is missing (e.g. truncated model
+ # output) must fail explicitly rather than silently treating the
+ # remainder as a valid code prompt, so callers can handle the malformed
+ # input intentionally.
+ base_message = BaseMessage(
+ role_name="test_role_name",
+ role_type=RoleType.USER,
+ meta_dict=dict(),
+ content="This is a text prompt.\n\n```python\nprint('unclosed')",
+ )
+ with pytest.raises(
+ ValueError, match="Unclosed code fence in message content"
+ ):
+ base_message.extract_text_and_code_prompts()
+
+
def test_base_message_to_dict(base_message: BaseMessage) -> None:
expected_dict = {
"role_name": "test_user",