🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
fix: Backend model tool call (#1624)
Isaac Jin4c5ba847f7dd
diff --git a/camel/agents/_utils.py b/camel/agents/_utils.pyindex da4ed8f9f..d219b6f3a 100644--- a/camel/agents/_utils.py+++ b/camel/agents/_utils.py@@ -15,14 +15,8 @@ import jsonimport loggingimport reimport textwrap-import uuidfrom typing import Any, Callable, Dict, List, Optional, Union-from openai.types.chat.chat_completion_message_tool_call import (- ChatCompletionMessageToolCall,- Function,-)-from camel.agents._types import ToolCallRequestfrom camel.toolkits import FunctionToolfrom camel.types import Choice@@ -74,73 +68,31 @@ def generate_tool_prompt(tool_schema_list: List[Dict[str, Any]]) -> str:return final_prompt-def _parse_tool_response(response: str) -> Optional[Dict[str, Any]]:- r"""Parses the tool response to extract the function name and- arguments.-- Args:- response (str): The response from the model containing the- function call.-- Returns:- Optional[Dict[str, Any]]: The parsed function name and arguments- if found, otherwise :obj:`None`.- """- function_regex = r"<function=(\w+)>(.*?)</function>"- match = re.search(function_regex, response)-- if match:- function_name, args_string = match.groups()- try:- args = json.loads(args_string)- return {"function": function_name, "arguments": args}- except json.JSONDecodeError as error:- logger.error(f"Error parsing function arguments: {error}")- return None- return None--def extract_tool_call(- self, response: Any-) -> Optional[ChatCompletionMessageToolCall]:+ content: str,+) -> Optional[Dict[str, Any]]:r"""Extract the tool call from the model response, if present.Args:response (Any): The model's response object.Returns:- Optional[ChatCompletionMessageToolCall]: The parsed tool call if- present, otherwise None.+ Optional[Dict[str, Any]]: The parsed tool call if present,+ otherwise None."""- # Check if the response contains tool calls- if (- self.has_tools- and not self.model_type.support_native_tool_calling- and "</function>" in response.choices[0].message.content- ):- parsed_content = _parse_tool_response(- response.choices[0].message.content- )- if parsed_content:- return ChatCompletionMessageToolCall(- id=str(uuid.uuid4()),- function=Function(- arguments=str(parsed_content["arguments"]).replace(- "'", '"'- ),- name=str(parsed_content["function"]),- ),- type="function",- )- elif (- self.has_tools- and self.model_type.support_native_tool_calling- and response.choices[0].message.tool_calls- ):- return response.choices[0].message.tool_calls[0]-- # No tool call found- return None+ function_regex = r"<function=(\w+)>(.*?)</function>"+ match = re.search(function_regex, content)++ if not match:+ return None++ function_name, args_string = match.groups()+ try:+ args = json.loads(args_string)+ return {"function": function_name, "arguments": args}+ except json.JSONDecodeError as error:+ logger.error(f"Error parsing function arguments: {error}")+ return Nonedef safe_model_dump(obj) -> Dict[str, Any]:diff --git a/camel/models/_utils.py b/camel/models/_utils.pyindex d727b6b88..462606efb 100644--- a/camel/models/_utils.py+++ b/camel/models/_utils.py@@ -21,7 +21,7 @@ from camel.messages import OpenAIMessagedef try_modify_message_with_format(message: OpenAIMessage,- response_format: Optional[Type[BaseModel]] = None,+ response_format: Optional[Type[BaseModel]],) -> None:r"""Modifies the content of the message to include the instruction of usingthe response format.@@ -51,7 +51,7 @@ def try_modify_message_with_format(Please generate a JSON response adhering to the following JSON schema:{json_schema}- Make sure the JSON response is valid and matches the EXACT structure defined in the schema. Your result should only be a valid json object, without any other text or comments.+ Make sure the JSON response is valid and matches the EXACT structure defined in the schema. Your result should ONLY be a valid json object, WITHOUT ANY OTHER TEXT OR COMMENTS.""" # noqa: E501)message["content"] = updated_promptdiff --git a/camel/models/aiml_model.py b/camel/models/aiml_model.pyindex 64c6c9a42..84246770c 100644--- a/camel/models/aiml_model.py+++ b/camel/models/aiml_model.py@@ -54,11 +54,7 @@ class AIMLModel(BaseModelBackend):(default: :obj:`None`)"""- @api_keys_required(- [- ("api_key", 'AIML_API_KEY'),- ]- )+ @api_keys_required([("api_key", "AIML_API_KEY")])def __init__(self,model_type: Union[ModelType, str],@@ -98,8 +94,9 @@ class AIMLModel(BaseModelBackend):) -> Dict[str, Any]:request_config = self.model_config_dict.copy()if tools:- request_config['tools'] = tools+ request_config["tools"] = toolsif response_format:+ # AIML API does not natively support response formattry_modify_message_with_format(messages[-1], response_format)return request_config@@ -109,7 +106,7 @@ class AIMLModel(BaseModelBackend):response_format: Optional[Type[BaseModel]] = None,tools: Optional[List[Dict[str, Any]]] = None,) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:- r"""Runs inference of OpenAI chat completion.+ r"""Runs inference of AIML chat completion.Args:messages (List[OpenAIMessage]): Message list with the chat history@@ -178,4 +175,4 @@ class AIMLModel(BaseModelBackend):Returns:bool: Whether the model is in stream mode."""- return self.model_config_dict.get('stream', False)+ return self.model_config_dict.get("stream", False)diff --git a/camel/models/groq_model.py b/camel/models/groq_model.pyindex 963535f01..546ca4faf 100644--- a/camel/models/groq_model.py+++ b/camel/models/groq_model.py@@ -12,7 +12,7 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import os-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Unionfrom openai import AsyncOpenAI, AsyncStream, OpenAI, Streamfrom pydantic import BaseModel@@ -20,6 +20,7 @@ from pydantic import BaseModelfrom camel.configs import GROQ_API_PARAMS, GroqConfigfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackend+from camel.models._utils import try_modify_message_with_formatfrom camel.types import (ChatCompletion,ChatCompletionChunk,@@ -52,11 +53,7 @@ class GroqModel(BaseModelBackend):(default: :obj:`None`)"""- @api_keys_required(- [- ("api_key", "GROQ_API_KEY"),- ]- )+ @api_keys_required([("api_key", "GROQ_API_KEY")])def __init__(self,model_type: Union[ModelType, str],@@ -99,27 +96,50 @@ class GroqModel(BaseModelBackend):self._token_counter = OpenAITokenCounter(ModelType.GPT_4O_MINI)return self._token_counter+ def _prepare_request(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Dict[str, Any]:+ request_config = self.model_config_dict.copy()+ if tools:+ request_config["tools"] = tools+ elif response_format:+ try_modify_message_with_format(messages[-1], response_format)+ request_config["response_format"] = {"type": "json_object"}++ return request_config+def _run(self,messages: List[OpenAIMessage],response_format: Optional[type[BaseModel]] = None,tools: Optional[List[Dict[str, Any]]] = None,) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:- r"""Runs inference of OpenAI chat completion.+ r"""Runs inference of Groq chat completion.Args:messages (List[OpenAIMessage]): Message list with the chat historyin OpenAI API format.+ response_format (Optional[Type[BaseModel]]): The format of the+ response.+ tools (Optional[List[Dict[str, Any]]]): The schema of the tools to+ use for the request.Returns:Union[ChatCompletion, Stream[ChatCompletionChunk]]:`ChatCompletion` in the non-stream mode, or`Stream[ChatCompletionChunk]` in the stream mode."""+ request_config = self._prepare_request(+ messages, response_format, tools+ )+response = self._client.chat.completions.create(messages=messages,model=self.model_type,- **self.model_config_dict,+ **request_config,)return response@@ -130,21 +150,29 @@ class GroqModel(BaseModelBackend):response_format: Optional[type[BaseModel]] = None,tools: Optional[List[Dict[str, Any]]] = None,) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:- r"""Runs inference of OpenAI chat completion.+ r"""Runs inference of Groq chat completion asynchronously.Args:messages (List[OpenAIMessage]): Message list with the chat historyin OpenAI API format.+ response_format (Optional[Type[BaseModel]]): The format of the+ response.+ tools (Optional[List[Dict[str, Any]]]): The schema of the tools to+ use for the request.Returns:Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:`ChatCompletion` in the non-stream mode, or`AsyncStream[ChatCompletionChunk]` in the stream mode."""+ request_config = self._prepare_request(+ messages, response_format, tools+ )+response = await self._async_client.chat.completions.create(messages=messages,model=self.model_type,- **self.model_config_dict,+ **request_config,)return responsediff --git a/camel/models/moonshot_model.py b/camel/models/moonshot_model.pyindex b53d2994a..344bd69a6 100644--- a/camel/models/moonshot_model.py+++ b/camel/models/moonshot_model.py@@ -21,6 +21,7 @@ from pydantic import BaseModelfrom camel.configs import MOONSHOT_API_PARAMS, MoonshotConfigfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackend+from camel.models._utils import try_modify_message_with_formatfrom camel.types import (ChatCompletion,ChatCompletionChunk,@@ -79,6 +80,19 @@ class MoonshotModel(BaseModelBackend):base_url=self._url,)+ def _prepare_request(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Dict[str, Any]:+ request_config = self.model_config_dict.copy()+ if tools:+ request_config["tools"] = tools+ elif response_format:+ try_modify_message_with_format(messages[-1], response_format)+ return request_config+def _run(self,messages: List[OpenAIMessage],@@ -87,7 +101,6 @@ class MoonshotModel(BaseModelBackend):) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:r"""Runs inference of Moonshot chat completion.-Args:messages (List[OpenAIMessage]): Message list with the chat historyin OpenAI API format.@@ -97,10 +110,14 @@ class MoonshotModel(BaseModelBackend):`ChatCompletion` in the non-stream mode, or`Stream[ChatCompletionChunk]` in the stream mode."""+ request_config = self._prepare_request(+ messages, response_format, tools+ )+response = self._client.chat.completions.create(messages=messages,model=self.model_type,- **self.model_config_dict,+ **request_config,)return responsediff --git a/camel/models/ollama_model.py b/camel/models/ollama_model.pyindex 1d38023ae..dc2936a29 100644--- a/camel/models/ollama_model.py+++ b/camel/models/ollama_model.py@@ -21,6 +21,7 @@ from pydantic import BaseModelfrom camel.configs import OLLAMA_API_PARAMS, OllamaConfigfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackend+from camel.models._utils import try_modify_message_with_formatfrom camel.types import (ChatCompletion,ChatCompletionChunk,@@ -126,79 +127,154 @@ class OllamaModel(BaseModelBackend):"input into Ollama model backend.")+ def _run(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ r"""Runs inference of Ollama chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.+ response_format (Optional[Type[BaseModel]]): The format of the+ response.+ tools (Optional[List[Dict[str, Any]]]): The schema of the tools to+ use for the request.++ Returns:+ Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `Stream[ChatCompletionChunk]` in the stream mode.+ """+ response_format = response_format or self.model_config_dict.get(+ "response_format", None+ )+ # For Ollama, the tool calling will be broken with response_format+ if response_format and not tools:+ return self._request_parse(messages, response_format, tools)+ else:+ return self._request_chat_completion(+ messages, response_format, tools+ )+async def _arun(self,messages: List[OpenAIMessage],response_format: Optional[Type[BaseModel]] = None,tools: Optional[List[Dict[str, Any]]] = None,) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:- r"""Runs inference of OpenAI chat completion.+ r"""Runs inference of Ollama chat completion in async mode.Args:messages (List[OpenAIMessage]): Message list with the chat historyin OpenAI API format.+ response_format (Optional[Type[BaseModel]]): The format of the+ response.+ tools (Optional[List[Dict[str, Any]]]): The schema of the tools to+ use for the request.Returns:Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:`ChatCompletion` in the non-stream mode, or`AsyncStream[ChatCompletionChunk]` in the stream mode."""- if self.model_config_dict.get("response_format"):- # stream is not supported in beta.chat.completions.parse- if "stream" in self.model_config_dict:- del self.model_config_dict["stream"]-- response = await self._async_client.beta.chat.completions.parse(- messages=messages,- model=self.model_type,- **self.model_config_dict,+ response_format = response_format or self.model_config_dict.get(+ "response_format", None+ )+ if response_format:+ return await self._arequest_parse(messages, response_format, tools)+ else:+ return await self._arequest_chat_completion(+ messages, response_format, tools)- return self._to_chat_completion(response)+ def _prepare_chat_completion_config(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Dict[str, Any]:+ request_config = self.model_config_dict.copy()- response = await self._async_client.chat.completions.create(+ if tools:+ request_config["tools"] = tools+ if response_format:+ try_modify_message_with_format(messages[-1], response_format)+ request_config["response_format"] = {"type": "json_object"}++ return request_config++ def _request_chat_completion(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ request_config = self._prepare_chat_completion_config(+ messages, response_format, tools+ )++ return self._client.chat.completions.create(messages=messages,model=self.model_type,- **self.model_config_dict,+ **request_config,)- return response- def _run(+ async def _arequest_chat_completion(self,messages: List[OpenAIMessage],response_format: Optional[Type[BaseModel]] = None,tools: Optional[List[Dict[str, Any]]] = None,- ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:- r"""Runs inference of OpenAI chat completion.+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ request_config = self._prepare_chat_completion_config(+ messages, response_format, tools+ )- Args:- messages (List[OpenAIMessage]): Message list with the chat history- in OpenAI API format.+ return await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **request_config,+ )- Returns:- Union[ChatCompletion, Stream[ChatCompletionChunk]]:- `ChatCompletion` in the non-stream mode, or- `Stream[ChatCompletionChunk]` in the stream mode.- """- if self.model_config_dict.get("response_format"):- # stream is not supported in beta.chat.completions.parse- if "stream" in self.model_config_dict:- del self.model_config_dict["stream"]-- response = self._client.beta.chat.completions.parse(- messages=messages,- model=self.model_type,- **self.model_config_dict,- )+ def _request_parse(+ self,+ messages: List[OpenAIMessage],+ response_format: Type[BaseModel],+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> ChatCompletion:+ request_config = self.model_config_dict.copy()++ request_config["response_format"] = response_format+ request_config.pop("stream", None)+ if tools is not None:+ request_config["tools"] = tools++ return self._client.beta.chat.completions.parse(+ messages=messages,+ model=self.model_type,+ **request_config,+ )++ async def _arequest_parse(+ self,+ messages: List[OpenAIMessage],+ response_format: Type[BaseModel],+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> ChatCompletion:+ request_config = self.model_config_dict.copy()- return self._to_chat_completion(response)+ request_config["response_format"] = response_format+ request_config.pop("stream", None)+ if tools is not None:+ request_config["tools"] = tools- response = self._client.chat.completions.create(+ return await self._async_client.beta.chat.completions.parse(messages=messages,model=self.model_type,- **self.model_config_dict,+ **request_config,)- return response@propertydef stream(self) -> bool:diff --git a/camel/models/qwen_model.py b/camel/models/qwen_model.pyindex 68f72836d..ac3143fbe 100644--- a/camel/models/qwen_model.py+++ b/camel/models/qwen_model.py@@ -107,10 +107,14 @@ class QwenModel(BaseModelBackend):`ChatCompletion` in the non-stream mode, or`AsyncStream[ChatCompletionChunk]` in the stream mode."""+ request_config = self._prepare_request(+ messages, response_format, tools+ )+response = await self._async_client.chat.completions.create(messages=messages,model=self.model_type,- **self.model_config_dict,+ **request_config,)return response