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(models): surface Ollama's real usage and truncation in FunctionGemmaModel (#4223)

Amir Fathi237b3b0332b7
diff --git a/camel/models/function_gemma_model.py b/camel/models/function_gemma_model.py
index 52a2902f6..6ed3e29f9 100644
--- a/camel/models/function_gemma_model.py
+++ b/camel/models/function_gemma_model.py
@@ -627,11 +627,29 @@ class FunctionGemmaModel(BaseModelBackend):
# return as string
return value
+ @staticmethod
+ def _map_done_reason(done_reason: Optional[str]) -> str:
+ r"""Map Ollama's done_reason to the OpenAI finish_reason vocabulary.
+
+ Args:
+ done_reason (Optional[str]): The ``done_reason`` field from
+ Ollama's ``/api/generate`` response.
+
+ Returns:
+ str: ``"length"`` when Ollama reports truncation, ``"stop"``
+ otherwise (including when ``done_reason`` is absent, which
+ preserves the prior default).
+ """
+ if done_reason == "length":
+ return "length"
+ return "stop"
+
def _to_chat_completion( # type: ignore[override]
self,
response_text: str,
model: str,
tools: Optional[List[Dict[str, Any]]] = None,
+ ollama_result: Optional[Dict[str, Any]] = None,
) -> ChatCompletion:
r"""Convert parsed response to OpenAI ChatCompletion format.
@@ -640,6 +658,10 @@ class FunctionGemmaModel(BaseModelBackend):
model (str): The model name.
tools (Optional[List[Dict[str, Any]]]): Available tools for
function name inference.
+ ollama_result (Optional[Dict[str, Any]]): The raw JSON body of
+ Ollama's ``/api/generate`` response, used to surface real
+ token usage (``prompt_eval_count``/``eval_count``) and the
+ truncation signal (``done_reason``). (default: :obj:`None`)
Returns:
ChatCompletion: OpenAI-compatible ChatCompletion object.
@@ -656,7 +678,14 @@ class FunctionGemmaModel(BaseModelBackend):
if tool_calls:
message["tool_calls"] = tool_calls
- finish_reason = "tool_calls" if tool_calls else "stop"
+ ollama_result = ollama_result or {}
+
+ if tool_calls:
+ finish_reason = "tool_calls"
+ else:
+ finish_reason = self._map_done_reason(
+ ollama_result.get("done_reason")
+ )
choice = dict(
index=0,
@@ -664,6 +693,9 @@ class FunctionGemmaModel(BaseModelBackend):
finish_reason=finish_reason,
)
+ prompt_tokens = ollama_result.get("prompt_eval_count") or 0
+ completion_tokens = ollama_result.get("eval_count") or 0
+
obj = ChatCompletion.construct(
id=f"chatcmpl-{uuid.uuid4().hex}",
choices=[choice],
@@ -671,22 +703,24 @@ class FunctionGemmaModel(BaseModelBackend):
model=model,
object="chat.completion",
usage=CompletionUsage(
- prompt_tokens=0,
- completion_tokens=0,
- total_tokens=0,
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ total_tokens=prompt_tokens + completion_tokens,
),
)
return obj
- def _call_ollama_generate(self, prompt: str) -> str:
+ def _call_ollama_generate(self, prompt: str) -> Dict[str, Any]:
r"""Call Ollama's /api/generate endpoint with raw prompt.
Args:
prompt (str): The formatted prompt string.
Returns:
- str: The model response text.
+ Dict[str, Any]: The parsed JSON body of Ollama's response,
+ including ``response``, ``done_reason``,
+ ``prompt_eval_count``, and ``eval_count``.
Raises:
RuntimeError: If the API request fails.
@@ -730,19 +764,20 @@ class FunctionGemmaModel(BaseModelBackend):
try:
response = self._call_client(self._client.post, url, json=data)
response.raise_for_status()
- result = response.json()
- return result.get("response", "")
+ return response.json()
except httpx.HTTPStatusError as e:
raise RuntimeError(f"Ollama API request failed: {e}")
- async def _acall_ollama_generate(self, prompt: str) -> str:
+ async def _acall_ollama_generate(self, prompt: str) -> Dict[str, Any]:
r"""Async call Ollama's /api/generate endpoint with raw prompt.
Args:
prompt (str): The formatted prompt string.
Returns:
- str: The model response text.
+ Dict[str, Any]: The parsed JSON body of Ollama's response,
+ including ``response``, ``done_reason``,
+ ``prompt_eval_count``, and ``eval_count``.
Raises:
RuntimeError: If the API request fails.
@@ -788,8 +823,7 @@ class FunctionGemmaModel(BaseModelBackend):
self._async_client.post, url, json=data
)
response.raise_for_status()
- result = response.json()
- return result.get("response", "")
+ return response.json()
except httpx.HTTPStatusError as e:
raise RuntimeError(f"Ollama API request failed: {e}")
@@ -827,11 +861,12 @@ class FunctionGemmaModel(BaseModelBackend):
prompt = self._format_messages(messages, tools)
logger.debug(f"FunctionGemma prompt:\n{prompt}")
- response_text = self._call_ollama_generate(prompt)
+ ollama_result = self._call_ollama_generate(prompt)
+ response_text = ollama_result.get("response", "")
logger.debug(f"FunctionGemma response:\n{response_text}")
response = self._to_chat_completion(
- response_text, str(self.model_type), tools
+ response_text, str(self.model_type), tools, ollama_result
)
update_current_observation(usage=response.usage)
return response
@@ -870,11 +905,12 @@ class FunctionGemmaModel(BaseModelBackend):
prompt = self._format_messages(messages, tools)
logger.debug(f"FunctionGemma prompt:\n{prompt}")
- response_text = await self._acall_ollama_generate(prompt)
+ ollama_result = await self._acall_ollama_generate(prompt)
+ response_text = ollama_result.get("response", "")
logger.debug(f"FunctionGemma response:\n{response_text}")
response = self._to_chat_completion(
- response_text, str(self.model_type), tools
+ response_text, str(self.model_type), tools, ollama_result
)
update_current_observation(usage=response.usage)
return response
diff --git a/test/models/test_function_gemma_model.py b/test/models/test_function_gemma_model.py
new file mode 100644
index 000000000..9735bdcfb
--- /dev/null
+++ b/test/models/test_function_gemma_model.py
@@ -0,0 +1,132 @@
+# ========= 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 unittest.mock import MagicMock
+
+import pytest
+
+from camel.models import FunctionGemmaModel
+
+
+def _model() -> FunctionGemmaModel:
+ return FunctionGemmaModel("functiongemma")
+
+
+ "done_reason,expected",
+ [
+ ("length", "length"),
+ ("stop", "stop"),
+ (None, "stop"),
+ ("unknown_future_value", "stop"),
+ ],
+)
+def test_map_done_reason(done_reason, expected):
+ assert FunctionGemmaModel._map_done_reason(done_reason) == expected
+
+
+def test_to_chat_completion_surfaces_real_usage_and_truncation():
+ r"""Ollama's real prompt_eval_count/eval_count/done_reason must reach
+ the returned ChatCompletion, not the hardcoded zero usage / 'stop'
+ finish_reason the backend used to return unconditionally."""
+ model = _model()
+
+ result = model._to_chat_completion(
+ "The answer is 4.",
+ "functiongemma",
+ tools=None,
+ ollama_result={
+ "response": "The answer is 4.",
+ "done": True,
+ "done_reason": "length",
+ "prompt_eval_count": 37,
+ "eval_count": 128,
+ },
+ )
+
+ assert result.usage.prompt_tokens == 37
+ assert result.usage.completion_tokens == 128
+ assert result.usage.total_tokens == 165
+ assert result.choices[0].finish_reason == "length"
+
+
+def test_to_chat_completion_tool_calls_override_done_reason():
+ r"""A parsed tool call must still win over done_reason, matching the
+ prior unconditional tool_calls behavior."""
+ model = _model()
+ tools = [
+ {
+ "type": "function",
+ "function": {"name": "get_weather", "parameters": {}},
+ }
+ ]
+
+ result = model._to_chat_completion(
+ "<start_function_call>call:get_weather{}<end_function_call>",
+ "functiongemma",
+ tools=tools,
+ ollama_result={
+ "done_reason": "length",
+ "prompt_eval_count": 10,
+ "eval_count": 5,
+ },
+ )
+
+ assert result.choices[0].finish_reason == "tool_calls"
+ assert result.usage.prompt_tokens == 10
+ assert result.usage.completion_tokens == 5
+
+
+def test_to_chat_completion_no_ollama_result_defaults_preserved():
+ r"""Callers that pass no ollama_result keep the old zero-usage/'stop'
+ defaults (backward compatible with any external caller of this
+ method)."""
+ model = _model()
+
+ result = model._to_chat_completion(
+ "hello", "functiongemma", tools=None, ollama_result=None
+ )
+
+ assert result.usage.prompt_tokens == 0
+ assert result.usage.completion_tokens == 0
+ assert result.usage.total_tokens == 0
+ assert result.choices[0].finish_reason == "stop"
+
+
+def test_run_plumbs_ollama_usage_and_truncation_end_to_end():
+ r"""End-to-end: a mocked /api/generate response with real usage and a
+ truncation done_reason must not be discarded by _run."""
+ model = _model()
+ model._client.post = MagicMock(
+ return_value=MagicMock(
+ raise_for_status=MagicMock(),
+ json=MagicMock(
+ return_value={
+ "response": "The answer is 4.",
+ "done": True,
+ "done_reason": "length",
+ "prompt_eval_count": 37,
+ "eval_count": 128,
+ }
+ ),
+ )
+ )
+
+ response = model._run(
+ messages=[{"role": "user", "content": "what is 2+2?"}],
+ tools=None,
+ )
+
+ assert response.usage.prompt_tokens == 37
+ assert response.usage.completion_tokens == 128
+ assert response.choices[0].finish_reason == "length"