diff --git a/camel/models/xai_model.py b/camel/models/xai_model.py index 2126476a83..b0c853d1e0 100644 --- a/camel/models/xai_model.py +++ b/camel/models/xai_model.py @@ -523,6 +523,7 @@ def _stream_to_chunks( """ chunk_id = "" model = str(self.model_type) + response = None tool_calls_emitted = False for response, chunk in stream_iter: chunk_id = chunk_id or (response.id if response.id else "") @@ -558,7 +559,7 @@ def _stream_to_chunks( ) # After stream ends, store state from the accumulated response - if response: + if response is not None: encrypted = response.encrypted_content reasoning = response.reasoning_content if encrypted: @@ -767,9 +768,7 @@ def _compute_delta_messages( # messages are genuinely new. ChatAgent's streaming # path may also record duplicate assistant messages, # so filtering by role is the safest approach. - delta = [ - m for m in delta if m.get("role") != "assistant" - ] + delta = [m for m in delta if m.get("role") != "assistant"] if delta: return delta diff --git a/test/models/test_xai_model.py b/test/models/test_xai_model.py new file mode 100644 index 0000000000..828f5d0cb3 --- /dev/null +++ b/test/models/test_xai_model.py @@ -0,0 +1,28 @@ +# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. ========= +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. ========= + +from types import MethodType + +from camel.models.xai_model import XAIModel + + +def test_stream_to_chunks_handles_empty_stream(): + model = XAIModel.__new__(XAIModel) + model.model_type = "grok-3" + model._last_encrypted_content = None + model._last_reasoning_content = None + model._save_response_chain = lambda *_args, **_kwargs: None + model._make_chunk = MethodType(lambda self, **kwargs: kwargs, model) + + assert list(XAIModel._stream_to_chunks(model, iter([]), 0)) == []