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: detect AsyncChatCompletionStreamManager by class name (#3743)

MkDev11babec47080e3
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index 75b2867ec..feecb78d6 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -1302,7 +1302,7 @@ class ChatAgent(BaseAgent):
def save_quoted(match):
quoted_parts.append(match.group(0))
- return f'__QUOTED_{len(quoted_parts)-1}__'
+ return f'__QUOTED_{len(quoted_parts) - 1}__'
line = re.sub(r'"[^"]*"', save_quoted, line)
line = re.sub(r'\s*\[[^\]]+\]\s*', ' ', line)
@@ -4251,7 +4251,6 @@ class ChatAgent(BaseAgent):
or (
hasattr(response, '__iter__')
and hasattr(response, '__enter__')
- and not hasattr(response, 'get_final_completion')
and not isinstance(response, ChatCompletion)
)
):
@@ -4298,8 +4297,11 @@ class ChatAgent(BaseAgent):
# Stream completed without tool calls
accumulated_tool_calls.clear()
break
- elif hasattr(response, 'get_final_completion'):
+ elif hasattr(response, '__enter__') and not hasattr(
+ response, '__iter__'
+ ):
# Handle structured output stream (ChatCompletionStreamManager)
+ # This catches context managers that aren't iterators
with response as stream: # type: ignore[union-attr]
parsed_object = None
@@ -5215,7 +5217,6 @@ class ChatAgent(BaseAgent):
or (
hasattr(response, '__aiter__')
and hasattr(response, '__aenter__')
- and not hasattr(response, 'get_final_completion')
and not isinstance(response, ChatCompletion)
)
):
@@ -5273,9 +5274,12 @@ class ChatAgent(BaseAgent):
# Stream completed without tool calls
accumulated_tool_calls.clear()
break
- elif hasattr(response, 'get_final_completion'):
+ elif hasattr(response, '__aenter__') and not hasattr(
+ response, '__aiter__'
+ ):
# Handle structured output stream
# (AsyncChatCompletionStreamManager)
+ # Catches async context managers that aren't async iterators
async with response as stream: # type: ignore[union-attr]
parsed_object = None
diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.py
index 51514b09c..151336100 100644
--- a/test/agents/test_chat_agent.py
+++ b/test/agents/test_chat_agent.py
@@ -103,7 +103,7 @@ def test_chat_agent(model, step_call_count=3):
assistant_without_sys_msg = ChatAgent(model=model)
assert str(assistant_with_sys_msg) == (
- "ChatAgent(doctor, " f"RoleType.ASSISTANT, {ModelType.DEFAULT})"
+ f"ChatAgent(doctor, RoleType.ASSISTANT, {ModelType.DEFAULT})"
)
assert str(assistant_without_sys_msg) == (
"ChatAgent(assistant, "
@@ -129,14 +129,20 @@ def test_chat_agent(model, step_call_count=3):
for i in range(step_call_count):
for user_msg in [user_msg_bm, user_msg_str]:
response = assistant.step(user_msg)
- assert isinstance(response.msgs, list), f"Error in round {i+1}"
- assert len(response.msgs) > 0, f"Error in round {i+1}"
+ assert isinstance(
+ response.msgs, list
+ ), f"Error in round {i + 1}"
+ assert len(response.msgs) > 0, f"Error in round {i + 1}"
assert isinstance(
response.terminated, bool
- ), f"Error in round {i+1}"
- assert response.terminated is False, f"Error in round {i+1}"
- assert isinstance(response.info, dict), f"Error in round {i+1}"
- assert response.info['id'] is not None, f"Error in round {i+1}"
+ ), f"Error in round {i + 1}"
+ assert response.terminated is False, f"Error in round {i + 1}"
+ assert isinstance(
+ response.info, dict
+ ), f"Error in round {i + 1}"
+ assert (
+ response.info['id'] is not None
+ ), f"Error in round {i + 1}"
@pytest.mark.model_backend
@@ -227,13 +233,13 @@ def test_chat_agent_step_with_structure_response(step_call_count=3):
response_content_keys = set(response_content_json.keys())
assert joke_response_keys.issubset(response_content_keys), (
- f"Error in calling round {i+1}: "
+ f"Error in calling round {i + 1}: "
f"Missing keys: {joke_response_keys - response_content_keys}"
)
for key in joke_response_keys:
assert key in response_content_json, (
- f"Error in calling round {i+1}: "
+ f"Error in calling round {i + 1}: "
f"Key {key} not found in response content"
)
@@ -366,7 +372,7 @@ def test_chat_agent_step_with_external_tools(step_call_count=3):
]
assert (
external_tool_call_requests[0].tool_name == "math_subtract"
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
@pytest.mark.model_backend
@@ -510,7 +516,7 @@ async def test_chat_agent_astep_with_external_tools(step_call_count=3):
]
assert (
external_tool_call_requests[0].tool_name == "math_subtract"
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
@pytest.mark.model_backend
@@ -588,8 +594,8 @@ def test_chat_agent_step_exceed_token_number(step_call_count=3):
for i in range(step_call_count):
response = assistant.step(user_msg)
- assert len(response.msgs) == 0, f"Error in calling round {i+1}"
- assert response.terminated, f"Error in calling round {i+1}"
+ assert len(response.msgs) == 0, f"Error in calling round {i + 1}"
+ assert response.terminated, f"Error in calling round {i + 1}"
@pytest.mark.model_backend
@@ -653,16 +659,16 @@ def test_chat_agent_multiple_return_messages(n, step_call_count=3):
for i in range(step_call_count):
assert (
assistant_with_sys_msg_response.msgs is not None
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert (
len(assistant_with_sys_msg_response.msgs) == n
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert (
assistant_without_sys_msg_response.msgs is not None
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert (
len(assistant_without_sys_msg_response.msgs) == n
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
@pytest.mark.model_backend
@@ -744,20 +750,20 @@ def test_chat_agent_stream_output(step_call_count=3):
stream_assistant_response = stream_assistant.step(user_msg)
for msg in stream_assistant_response.msgs:
- assert len(msg.content) > 0, f"Error in calling round {i+1}"
+ assert len(msg.content) > 0, f"Error in calling round {i + 1}"
stream_usage = stream_assistant_response.info["usage"]
assert (
stream_usage["completion_tokens"] > 0
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert (
stream_usage["prompt_tokens"] > 0
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert (
stream_usage["total_tokens"]
== stream_usage["completion_tokens"]
+ stream_usage["prompt_tokens"]
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
@pytest.mark.model_backend
@@ -1032,19 +1038,19 @@ def test_tool_calling_sync(step_call_count=3):
call for call in agent_response.info['tool_calls']
]
- assert len(tool_calls) > 0, f"Error in calling round {i+1}"
+ assert len(tool_calls) > 0, f"Error in calling round {i + 1}"
assert str(tool_calls[0]).startswith(
"Tool Execution"
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert (
tool_calls[0].tool_name == "math_multiply"
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert tool_calls[0].args == {
"a": 2,
"b": 8,
'decimal_places': 0,
- }, f"Error in calling round {i+1}"
- assert tool_calls[0].result == 16, f"Error in calling round {i+1}"
+ }, f"Error in calling round {i + 1}"
+ assert tool_calls[0].result == 16, f"Error in calling round {i + 1}"
@pytest.mark.model_backend
@@ -1161,13 +1167,13 @@ async def test_tool_calling_math_async(step_call_count=3):
assert (
tool_calls[0].tool_name == "math_multiply"
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert tool_calls[0].args == {
"a": 2,
"b": 8,
'decimal_places': 0,
- }, f"Error in calling round {i+1}"
- assert tool_calls[0].result == 16, f"Error in calling round {i+1}"
+ }, f"Error in calling round {i + 1}"
+ assert tool_calls[0].result == 16, f"Error in calling round {i + 1}"
@pytest.mark.model_backend
@@ -1247,18 +1253,18 @@ async def test_tool_calling_async(step_call_count=3):
tool_calls = agent_response.info['tool_calls']
- assert tool_calls, f"Error in calling round {i+1}"
+ assert tool_calls, f"Error in calling round {i + 1}"
assert str(tool_calls[0]).startswith(
"Tool Execution"
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert (
tool_calls[0].tool_name == "async_sleep"
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
assert tool_calls[0].args == {
'second': 1
- }, f"Error in calling round {i+1}"
- assert tool_calls[0].result == 1, f"Error in calling round {i+1}"
+ }, f"Error in calling round {i + 1}"
+ assert tool_calls[0].result == 1, f"Error in calling round {i + 1}"
def test_response_words_termination(step_call_count=3):
@@ -1286,11 +1292,11 @@ def test_response_words_termination(step_call_count=3):
for i in range(step_call_count):
agent_response = agent.step(user_msg)
- assert agent.terminated, f"Error in calling round {i+1}"
- assert agent_response.terminated, f"Error in calling round {i+1}"
+ assert agent.terminated, f"Error in calling round {i + 1}"
+ assert agent_response.terminated, f"Error in calling round {i + 1}"
assert (
"goodbye" in agent_response.info['termination_reasons'][0]
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
def test_chat_agent_vision(step_call_count=3):
@@ -1358,7 +1364,7 @@ def test_chat_agent_vision(step_call_count=3):
agent_response = agent.step(user_msg)
assert (
agent_response.msgs[0].content == "Yes."
- ), f"Error in calling round {i+1}"
+ ), f"Error in calling round {i + 1}"
@pytest.mark.model_backend
@@ -1759,3 +1765,75 @@ async def test_chat_agent_async_stream_with_async_generator_tool_calls():
break
assert tool_calls_found, "Tool calls should be found in responses"
+
+
+def test_chat_agent_stream_with_structured_output():
+ r"""Test streaming with structured output (response_format).
+
+ This is an e2e test for the fix that properly detects and handles
+ ChatCompletionStreamManager returned by OpenAI when using
+ streaming + structured output together.
+ """
+
+ class MathResult(BaseModel):
+ answer: int = Field(description="The numerical answer")
+ explanation: str = Field(description="Brief explanation")
+
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4_1,
+ model_config_dict={"stream": True},
+ )
+
+ agent = ChatAgent(
+ system_message="You are a helpful math assistant.",
+ model=model,
+ )
+
+ # Stream with structured output - this triggers ChatCompletionStreamManager
+ responses = []
+ for response in agent.step("What is 2 + 2?", response_format=MathResult):
+ responses.append(response)
+
+ assert len(responses) > 1, "Should receive multiple streaming chunks"
+ assert responses[-1].msg.parsed.answer == 4
+ assert responses[-1].msg.parsed.explanation
+
+
+async def test_chat_agent_async_stream_with_structured_output():
+ r"""Test async streaming with structured output (response_format).
+
+ This is an e2e test for the fix that properly detects and handles
+ AsyncChatCompletionStreamManager returned by OpenAI when using
+ async streaming + structured output together.
+ """
+
+ class MathResult(BaseModel):
+ answer: int = Field(description="The numerical answer")
+ explanation: str = Field(description="Brief explanation")
+
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4_1,
+ model_config_dict={"stream": True},
+ )
+
+ agent = ChatAgent(
+ system_message="You are a helpful math assistant.",
+ model=model,
+ )
+
+ # Async stream with structured output - triggers
+ # AsyncChatCompletionStreamManager
+ responses = []
+ async for response in await agent.astep(
+ "What is 3 + 3?", response_format=MathResult
+ ):
+ responses.append(response)
+
+ assert len(responses) > 1, "Should receive multiple streaming chunks"
+ assert responses[-1].msg.parsed.answer == 6
+ assert responses[-1].msg.parsed.explanation