🐫 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
refactor: ChatAgent (#1424)
Isaac Jin0e849571b203
diff --git a/camel/agents/_types.py b/camel/agents/_types.pynew file mode 100644index 000000000..0ce37c6d1--- /dev/null+++ b/camel/agents/_types.py@@ -0,0 +1,41 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+from typing import Any, Dict, List, Optional, Union++from openai import AsyncStream, Stream+from pydantic import BaseModel, ConfigDict++from camel.messages import BaseMessage+from camel.types import ChatCompletion+++class ToolCallRequest(BaseModel):+ r"""The request for tool calling."""++ tool_name: str+ args: Dict[str, Any]+ tool_call_id: str+++class ModelResponse(BaseModel):+ r"""The response from the model."""++ model_config = ConfigDict(arbitrary_types_allowed=True)++ response: Union[ChatCompletion, Stream, AsyncStream]+ tool_call_request: Optional[ToolCallRequest]+ output_messages: List[BaseMessage]+ finish_reasons: List[str]+ usage_dict: Dict[str, Any]+ response_id: strdiff --git a/camel/agents/_utils.py b/camel/agents/_utils.pynew file mode 100644index 000000000..da4ed8f9f--- /dev/null+++ b/camel/agents/_utils.py@@ -0,0 +1,236 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import json+import logging+import re+import textwrap+import uuid+from 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 ToolCallRequest+from camel.toolkits import FunctionTool+from camel.types import Choice+from camel.types.agents import ToolCallingRecord++logger = logging.getLogger(__name__)+++def generate_tool_prompt(tool_schema_list: List[Dict[str, Any]]) -> str:+ r"""Generates a tool prompt based on the provided tool schema list.++ Returns:+ str: A string representing the tool prompt.+ """+ tool_prompts = []++ for tool in tool_schema_list:+ tool_info = tool["function"]+ tool_name = tool_info["name"]+ tool_description = tool_info["description"]+ tool_json = json.dumps(tool_info, indent=4)++ prompt = (+ f"Use the function '{tool_name}' to '{tool_description}':\n"+ f"{tool_json}\n"+ )+ tool_prompts.append(prompt)++ tool_prompt_str = "\n".join(tool_prompts)++ final_prompt = textwrap.dedent(+ f"""\+ You have access to the following functions:++ {tool_prompt_str}++ If you choose to call a function ONLY reply in the following format with no prefix or suffix:++ <function=example_function_name>{{"example_name": "example_value"}}</function>++ Reminder:+ - Function calls MUST follow the specified format, start with <function= and end with </function>+ - Required parameters MUST be specified+ - Only call one function at a time+ - Put the entire function call reply on one line+ - If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls.+ """ # noqa: E501+ )+ 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]:+ 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.+ """+ # 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+++def safe_model_dump(obj) -> Dict[str, Any]:+ r"""Safely dump a Pydantic model to a dictionary.++ This method attempts to use the `model_dump` method if available,+ otherwise it falls back to the `dict` method.+ """+ # Check if the `model_dump` method exists (Pydantic v2)+ if hasattr(obj, "model_dump"):+ return obj.model_dump()+ # Fallback to `dict()` method (Pydantic v1)+ elif hasattr(obj, "dict"):+ return obj.dict()+ else:+ raise TypeError("The object is not a Pydantic model")+++def convert_to_function_tool(+ tool: Union[FunctionTool, Callable],+) -> FunctionTool:+ r"""Convert a tool to a FunctionTool from Callable."""+ return tool if isinstance(tool, FunctionTool) else FunctionTool(tool)+++def convert_to_schema(+ tool: Union[FunctionTool, Callable, Dict[str, Any]],+) -> Dict[str, Any]:+ r"""Convert a tool to a schema from Callable or FunctionTool."""+ if isinstance(tool, FunctionTool):+ return tool.get_openai_tool_schema()+ elif callable(tool):+ return FunctionTool(tool).get_openai_tool_schema()+ else:+ return tool+++def get_info_dict(+ session_id: Optional[str],+ usage: Optional[Dict[str, int]],+ termination_reasons: List[str],+ num_tokens: int,+ tool_calls: List[ToolCallingRecord],+ external_tool_call_request: Optional[ToolCallRequest] = None,+) -> Dict[str, Any]:+ r"""Returns a dictionary containing information about the chat session.++ Args:+ session_id (str, optional): The ID of the chat session.+ usage (Dict[str, int], optional): Information about the usage of+ the LLM.+ termination_reasons (List[str]): The reasons for the termination+ of the chat session.+ num_tokens (int): The number of tokens used in the chat session.+ tool_calls (List[ToolCallingRecord]): The list of function+ calling records, containing the information of called tools.+ external_tool_call_request (Optional[ToolCallRequest]): The+ request for external tool call.+++ Returns:+ Dict[str, Any]: The chat session information.+ """+ return {+ "id": session_id,+ "usage": usage,+ "termination_reasons": termination_reasons,+ "num_tokens": num_tokens,+ "tool_calls": tool_calls,+ "external_tool_call_request": external_tool_call_request,+ }+++def handle_logprobs(choice: Choice) -> Optional[List[Dict[str, Any]]]:+ if choice.logprobs is None:+ return None++ tokens_logprobs = choice.logprobs.content++ if tokens_logprobs is None:+ return None++ return [+ {+ "token": token_logprob.token,+ "logprob": token_logprob.logprob,+ "top_logprobs": [+ (top_logprob.token, top_logprob.logprob)+ for top_logprob in token_logprob.top_logprobs+ ],+ }+ for token_logprob in tokens_logprobs+ ]diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 03cd20b3d..e130a86a0 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -15,8 +15,7 @@ from __future__ import annotationsimport jsonimport logging-import re-import uuid+import textwrapfrom collections import defaultdictfrom typing import (TYPE_CHECKING,@@ -25,15 +24,25 @@ from typing import (Dict,List,Optional,- Tuple,+ Set,Type,Union,)-from openai.types.chat import ChatCompletionMessageToolCall-from openai.types.chat.chat_completion_message_tool_call import Function+from openai import (+ AsyncStream,+ Stream,+)from pydantic import BaseModel, ValidationError+from camel.agents._types import ModelResponse, ToolCallRequest+from camel.agents._utils import (+ convert_to_function_tool,+ convert_to_schema,+ get_info_dict,+ handle_logprobs,+ safe_model_dump,+)from camel.agents.base import BaseAgentfrom camel.memories import (AgentMemory,@@ -48,7 +57,9 @@ from camel.models import (ModelManager,ModelProcessingError,)+from camel.prompts import TextPromptfrom camel.responses import ChatAgentResponse+from camel.toolkits import FunctionToolfrom camel.types import (ChatCompletion,ChatCompletionChunk,@@ -57,19 +68,11 @@ from camel.types import (OpenAIBackendRole,RoleType,)-from camel.utils import (- func_string_to_callable,- generate_prompt_for_structured_output,- get_model_encoding,- get_pydantic_object_schema,- json_to_function_code,-)+from camel.types.agents import ToolCallingRecord+from camel.utils import get_model_encodingif TYPE_CHECKING:- from openai import Stream-from camel.terminators import ResponseTerminator- from camel.toolkits import FunctionToollogger = logging.getLogger(__name__)@@ -86,41 +89,15 @@ except (ImportError, AttributeError):from camel.utils import track_agent-class ToolCallingRecord(BaseModel):- r"""Historical records of tools called in the conversation.-- Attributes:- tool_name (str): The name of the tool being called.- args (Dict[str, Any]): The dictionary of arguments passed to- the tools.- result (Any): The execution result of calling this tool.- tool_call_id (str): The ID of the tool call, if available.- """-- tool_name: str- args: Dict[str, Any]- result: Any- tool_call_id: str-- def __str__(self) -> str:- r"""Overridden version of the string function.-- Returns:- str: Modified string to represent the tool calling.- """- return (- f"Tool Execution: {self.tool_name}\n"- f"\tArgs: {self.args}\n"- f"\tResult: {self.result}\n"- )-- def as_dict(self) -> dict[str, Any]:- r"""Returns the function calling record as a dictionary.-- Returns:- dict[str, Any]: The function calling record as a dictionary.+SIMPLE_FORMAT_PROMPT = TextPrompt(+ textwrap.dedent(+ """\+ Please format the following content:++ {content}"""- return self.model_dump()+ )+)@track_agent(name="ChatAgent")@@ -148,11 +125,12 @@ class ChatAgent(BaseAgent):tools (Optional[List[Union[FunctionTool, Callable]]], optional): Listof available :obj:`FunctionTool` or :obj:`Callable`. (default::obj:`None`)- external_tools (Optional[List[Union[FunctionTool, Callable]]],- optional): List of external tools (:obj:`FunctionTool` or or- :obj:`Callable`) bind to one chat agent. When these tools are- called, the agent will directly return the request instead of- processing it. (default: :obj:`None`)+ external_tools (Optional[List[Union[FunctionTool, Callable,+ Dict[str, Any]]]], optional): List of external tools+ (:obj:`FunctionTool` or :obj:`Callable` or :obj:`Dict[str, Any]`)+ bind to one chat agent. When these tools are called, the agent will+ directly return the request instead of processing it.+ (default: :obj:`None`)response_terminators (List[ResponseTerminator], optional): List of:obj:`ResponseTerminator` bind to one chat agent.(default: :obj:`None`)@@ -173,265 +151,164 @@ class ChatAgent(BaseAgent):token_limit: Optional[int] = None,output_language: Optional[str] = None,tools: Optional[List[Union[FunctionTool, Callable]]] = None,- external_tools: Optional[List[Union[FunctionTool, Callable]]] = None,+ external_tools: Optional[+ List[Union[FunctionTool, Callable, Dict[str, Any]]]+ ] = None,response_terminators: Optional[List[ResponseTerminator]] = None,scheduling_strategy: str = "round_robin",single_iteration: bool = False,) -> None:- # Initialize the system message, converting string to BaseMessage if needed- if isinstance(system_message, str):- system_message = BaseMessage.make_assistant_message(- role_name='Assistant', content=system_message- )-- self.orig_sys_message: Optional[BaseMessage] = system_message- self._system_message: Optional[BaseMessage] = system_message- self.role_name: str = (- getattr(system_message, 'role_name', None) or "assistant"- )- self.role_type: RoleType = (- getattr(system_message, 'role_type', None) or RoleType.ASSISTANT- )+ # Set up model backendself.model_backend = ModelManager(- model- if model is not None- else ModelFactory.create(- model_platform=ModelPlatformType.DEFAULT,- model_type=ModelType.DEFAULT,+ (+ model+ if model is not None+ else ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ )),scheduling_strategy=scheduling_strategy,)self.model_type = self.model_backend.model_type- # Initialize tools- self.tools: List[FunctionTool] = (- self._initialize_tools(tools) if tools else []- )- self.external_tools: List[FunctionTool] = (- self._initialize_tools(external_tools) if external_tools else []- )- self.external_tool_names: List[str] = [- tool.get_function_name() for tool in self.external_tools- ]- self.all_tools = self.tools + self.external_tools or []-- # Create tool dictionaries and configure backend tools if necessary- self.tool_dict = {- tool.get_function_name(): tool for tool in self.all_tools- }-- # If the user set tools from `ChatAgent`, it will override the- # configured tools in `BaseModelBackend`.- if self.all_tools:- logger.warning(- "Overriding the configured tools in `BaseModelBackend` with the tools from `ChatAgent`."- )- tool_schema_list = [- tool.get_openai_tool_schema() for tool in self.all_tools- ]- self.model_backend.model_config_dict['tools'] = tool_schema_list-- self.model_token_limit = token_limit or self.model_backend.token_limit+ # Set up memorycontext_creator = ScoreBasedContextCreator(self.model_backend.token_counter,- self.model_token_limit,+ token_limit or self.model_backend.token_limit,)self.memory: AgentMemory = memory or ChatHistoryMemory(context_creator, window_size=message_window_size)- self.output_language: Optional[str] = output_language- if self.output_language is not None:- self.set_output_language(self.output_language)-- self.terminated: bool = False- self.response_terminators = response_terminators or []+ # Set up system message and initialize messages+ self._original_system_message = (+ BaseMessage.make_assistant_message(+ role_name="Assistant", content=system_message+ )+ if isinstance(system_message, str)+ else system_message+ )+ self._output_language = output_language+ self._system_message = (+ self._generate_system_message_for_output_language()+ )self.init_messages()- self.tool_prompt_added = False- self.single_iteration = single_iteration- def _initialize_tools(- self, tools: List[Union[FunctionTool, Callable]]- ) -> List[FunctionTool]:- r"""Helper method to initialize tools as FunctionTool instances."""- from camel.toolkits import FunctionTool-- func_tools = []- for tool in tools:- if not isinstance(tool, FunctionTool):- tool = FunctionTool(tool)- func_tools.append(tool)- return func_tools-- def add_tool(- self, tool: Union[FunctionTool, Callable], is_external: bool = False- ) -> None:- r"""Add a tool to the agent, specifying if it's an external tool."""- # Initialize the tool- initialized_tool = self._initialize_tools([tool])-- # Update tools or external tools based on is_external flag- if is_external:- self.external_tools = self.external_tools + initialized_tool- self.external_tool_names.extend(- tool.get_function_name() for tool in initialized_tool- )- else:- self.tools = self.tools + initialized_tool+ # Set up role name and role type+ self.role_name: str = (+ getattr(self.system_message, "role_name", None) or "assistant"+ )+ self.role_type: RoleType = (+ getattr(self.system_message, "role_type", None)+ or RoleType.ASSISTANT+ )- # Rebuild all_tools, and tool_dict- self.all_tools = self.tools + self.external_tools- self.tool_dict = {- tool.get_function_name(): tool for tool in self.all_tools+ # Set up tools+ self._internal_tools = {+ tool.get_function_name(): tool+ for tool in [+ convert_to_function_tool(tool) for tool in (tools or [])+ ]}- tool_schema_list = [- tool.get_openai_tool_schema() for tool in self.all_tools- ]- self.model_backend.model_config_dict['tools'] = tool_schema_list+ self._external_tool_schemas = {+ tool_schema["function"]["name"]: tool_schema+ for tool_schema in [+ convert_to_schema(tool) for tool in (external_tools or [])+ ]+ }- def remove_tool(self, tool_name: str, is_external: bool = False) -> bool:- r"""Remove a tool by name, specifying if it's an external tool."""- tool_list = self.external_tools if is_external else self.tools- if not tool_list:- return False+ # Set up other properties+ self.terminated = False+ self.response_terminators = response_terminators or []+ self.single_iteration = single_iteration- for tool in tool_list:- if tool.get_function_name() == tool_name:- tool_list.remove(tool)- if is_external:- self.external_tool_names.remove(tool_name)- # Reinitialize the tool dictionary- self.all_tools = (self.tools or []) + (- self.external_tools or []- )- self.tool_dict = {- tool.get_function_name(): tool for tool in self.all_tools- }- tool_schema_list = [- tool.get_openai_tool_schema() for tool in self.all_tools- ]- self.model_backend.model_config_dict['tools'] = (- tool_schema_list- )- return True- return False+ def reset(self):+ r"""Resets the :obj:`ChatAgent` to its initial state."""+ self.terminated = False+ self.init_messages()+ for terminator in self.response_terminators:+ terminator.reset()- def list_tools(self) -> dict:- r"""List all tools, separated into normal and external tools."""- normal_tools = [- tool.get_function_name() for tool in (self.tools or [])- ]- external_tools = [- tool.get_function_name() for tool in (self.external_tools or [])- ]+ @property+ def system_message(self) -> Optional[BaseMessage]:+ r"""Returns the system message for the agent."""+ return self._system_message- return {"normal_tools": normal_tools, "external_tools": external_tools}+ @property+ def tool_dict(self) -> Dict[str, FunctionTool]:+ r"""Returns a dictionary of internal tools."""+ return self._internal_tools- # ruff: noqa: E501- def _generate_tool_prompt(self, tool_schema_list: List[Dict]) -> str:- r"""Generates a tool prompt based on the provided tool schema list.+ @property+ def output_language(self) -> Optional[str]:+ r"""Returns the output language for the agent."""+ return self._output_language- Args:- tool_schema_list (List[Dict]): A list of dictionaries, each- containing a tool schema.+ @output_language.setter+ def output_language(self, value: str) -> None:+ r"""Set the output language for the agent.- Returns:- str: A string representing the tool prompt.+ Note that this will clear the message history."""- tool_prompts = []-- for tool in tool_schema_list:- tool_info = tool['function']- tool_name = tool_info['name']- tool_description = tool_info['description']- tool_json = json.dumps(tool_info, indent=4)-- prompt = f"Use the function '{tool_name}' to '{tool_description}':\n{tool_json}\n"- tool_prompts.append(prompt)-- tool_prompt_str = "\n".join(tool_prompts)-- final_prompt = f"""- You have access to the following functions:+ self._output_language = value+ self._system_message = (+ self._generate_system_message_for_output_language()+ )+ self.init_messages()- {tool_prompt_str}+ def _get_full_tool_schemas(self) -> List[Dict[str, Any]]:+ r"""Returns a list of tool schemas of all tools, including internal+ and external tools.+ """+ return list(self._external_tool_schemas.values()) + [+ func_tool.get_openai_tool_schema()+ for func_tool in self._internal_tools.values()+ ]- If you choose to call a function ONLY reply in the following format with no- prefix or suffix:+ def _get_external_tool_names(self) -> Set[str]:+ r"""Returns a set of external tool names."""+ return set(self._external_tool_schemas.keys())- <function=example_function_name>{{"example_name": "example_value"}}</function>+ def add_tool(self, tool: Union[FunctionTool, Callable]) -> None:+ r"""Add a tool to the agent."""+ new_tool = convert_to_function_tool(tool)+ self._internal_tools[new_tool.get_function_name()] = new_tool- Reminder:- - Function calls MUST follow the specified format, start with <function= and end with </function>- - Required parameters MUST be specified- - Only call one function at a time- - Put the entire function call reply on one line- - If there is no function call available, answer the question like normal- with your current knowledge and do not tell the user about function calls- """- return final_prompt+ def add_external_tool(+ self, tool: Union[FunctionTool, Callable, Dict[str, Any]]+ ) -> None:+ new_tool_schema = convert_to_schema(tool)+ self._external_tool_schemas[new_tool_schema["name"]] = new_tool_schema- def _parse_tool_response(self, response: str):- r"""Parses the tool response to extract the function name and- arguments.+ def remove_tool(self, tool_name: str) -> bool:+ r"""Remove a tool from the agent by name.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 reset(self):- r"""Resets the :obj:`ChatAgent` to its initial state."""- self.terminated = False- self.init_messages()- for terminator in self.response_terminators:- terminator.reset()-- @property- def system_message(self) -> Optional[BaseMessage]:- r"""The getter method for the property :obj:`system_message`.+ tool_name (str): The name of the tool to remove.Returns:- Optional[BaseMessage]: The system message of this agent if set,- else :obj:`None`.+ bool: Whether the tool was successfully removed."""- return self._system_message+ if tool_name in self._internal_tools:+ del self._internal_tools[tool_name]+ return True+ return False- @system_message.setter- def system_message(self, message: BaseMessage) -> None:- r"""The setter method for the property :obj:`system_message`.+ def remove_external_tool(self, tool_name: str) -> bool:+ r"""Remove an external tool from the agent by name.Args:- message (BaseMessage): The message to be set as the- new system message of this agent.- """- self._system_message = message-- def is_tools_added(self) -> bool:- r"""Whether tool calling is enabled for this agent.+ tool_name (str): The name of the tool to remove.Returns:- bool: Whether tool calling is enabled for this agent, determined- by whether the dictionary of tools is empty.+ bool: Whether the tool was successfully removed."""- return len(self.tool_dict) > 0+ if tool_name in self._external_tool_schemas:+ del self._external_tool_schemas[tool_name]+ return True+ return Falsedef update_memory(self, message: BaseMessage, role: OpenAIBackendRole@@ -447,94 +324,41 @@ class ChatAgent(BaseAgent):MemoryRecord(message=message, role_at_backend=role))- def set_output_language(self, output_language: str) -> BaseMessage:- r"""Sets the output language for the system message. This method- updates the output language for the system message. The output- language determines the language in which the output text should be- generated.+ def _generate_system_message_for_output_language(+ self,+ ) -> Optional[BaseMessage]:+ r"""Generate a new system message with the output language prompt.- Args:- output_language (str): The desired output language.+ The output language determines the language in which the output text+ should be generated.Returns:- BaseMessage: The updated system message object.+ BaseMessage: The new system message."""- self.output_language = output_language+ if not self._output_language:+ return self._original_system_message+language_prompt = ("\nRegardless of the input language, "- f"you must output text in {output_language}."+ f"you must output text in {self._output_language}.")- if self.orig_sys_message is not None:- content = self.orig_sys_message.content + language_prompt- self._system_message = self.orig_sys_message.create_new_instance(- content- )++ if self._original_system_message is not None:+ content = self._original_system_message.content + language_prompt+ return self._original_system_message.create_new_instance(content)else:- self._system_message = BaseMessage.make_assistant_message(+ return BaseMessage.make_assistant_message(role_name="Assistant",content=language_prompt,)- system_record = MemoryRecord(- message=self._system_message,- role_at_backend=OpenAIBackendRole.SYSTEM,- )- self.memory.clear()- self.memory.write_record(system_record)- return self._system_message-- def get_info(- self,- session_id: Optional[str],- usage: Optional[Dict[str, int]],- termination_reasons: List[str],- num_tokens: int,- tool_calls: List[ToolCallingRecord],- external_tool_request: Optional[ChatCompletionMessageToolCall] = None,- ) -> Dict[str, Any]:- r"""Returns a dictionary containing information about the chat session.-- Args:- session_id (str, optional): The ID of the chat session.- usage (Dict[str, int], optional): Information about the usage of- the LLM.- termination_reasons (List[str]): The reasons for the termination- of the chat session.- num_tokens (int): The number of tokens used in the chat session.- tool_calls (List[ToolCallingRecord]): The list of function- calling records, containing the information of called tools.- external_tool_request- (Optional[ChatCompletionMessageToolCall], optional):- The tool calling request of external tools from the model.- These requests are directly returned to the user instead of- being processed by the agent automatically.- (default: :obj:`None`)-- Returns:- Dict[str, Any]: The chat session information.- """- return {- "id": session_id,- "usage": usage,- "termination_reasons": termination_reasons,- "num_tokens": num_tokens,- "tool_calls": tool_calls,- "external_tool_request": external_tool_request,- }-def init_messages(self) -> None:r"""Initializes the stored messages list with the current systemmessage."""- if self._system_message is not None:- system_record = MemoryRecord(- message=self._system_message,- role_at_backend=OpenAIBackendRole.SYSTEM,- )- self.memory.clear()- self.memory.write_record(system_record)- else:- self.memory.clear()+ self.memory.clear()+ if self.system_message is not None:+ self.update_memory(self.system_message, OpenAIBackendRole.SYSTEM)def record_message(self, message: BaseMessage) -> None:r"""Records the externally provided message into the agent memory as if@@ -547,6 +371,77 @@ class ChatAgent(BaseAgent):"""self.update_memory(message, OpenAIBackendRole.ASSISTANT)+ def _try_format_message(+ self, message: BaseMessage, response_format: Type[BaseModel]+ ) -> bool:+ r"""Try to format the message if needed.++ Returns:+ bool: Whether the message is formatted successfully (or no format+ is needed).+ """+ if message.parsed:+ return True++ try:+ message.parsed = response_format.model_validate_json(+ message.content+ )+ return True+ except ValidationError:+ return False++ def _format_response_if_needed(+ self,+ response: ModelResponse,+ response_format: Optional[Type[BaseModel]] = None,+ ) -> None:+ r"""Format the response if needed.++ This function won't format the response under the following cases:+ 1. The response format is None (not provided)+ 2. The response is empty+ """+ if response_format is None:+ return++ for message in response.output_messages:+ if self._try_format_message(message, response_format):+ continue++ prompt = SIMPLE_FORMAT_PROMPT.format(content=message.content)+ openai_message: OpenAIMessage = {"role": "user", "content": prompt}+ # Explicitly set the tools to empty list to avoid calling tools+ response = self._get_model_response(+ [openai_message], 0, response_format, []+ )+ message.content = response.output_messages[0].content+ if not self._try_format_message(message, response_format):+ logger.warning(f"Failed to parse response: {message.content}")++ async def _aformat_response_if_needed(+ self,+ response: ModelResponse,+ response_format: Optional[Type[BaseModel]] = None,+ ) -> None:+ r"""Format the response if needed."""++ if response_format is None:+ return++ for message in response.output_messages:+ self._try_format_message(message, response_format)+ if message.parsed:+ continue++ prompt = SIMPLE_FORMAT_PROMPT.format(content=message.content)+ openai_message: OpenAIMessage = {"role": "user", "content": prompt}+ response = await self._aget_model_response(+ [openai_message], 0, response_format, []+ )+ message.content = response.output_messages[0].content+ self._try_format_message(message, response_format)+def step(self,input_message: Union[BaseMessage, str],@@ -569,289 +464,59 @@ class ChatAgent(BaseAgent):flag, and session information."""- if (- self.model_backend.model_config_dict.get("response_format")- and response_format- ):- logger.warning(- f"Overriding the response format with {response_format}."- )-- self.original_model_dict = self.model_backend.model_config_dict- model_response_format_modified = False- if (- response_format- and self.model_type.support_native_structured_output- ):- self.model_backend.model_config_dict = (- self.original_model_dict.copy()- )- self.model_backend.model_config_dict["response_format"] = (- response_format- )- model_response_format_modified = True-# Convert input message to BaseMessage if necessaryif isinstance(input_message, str):input_message = BaseMessage.make_user_message(- role_name='User', content=input_message+ role_name="User", content=input_message)- # Handle tool prompt injection if needed- if (- self.is_tools_added()- and not self.model_type.support_native_tool_calling- and not self.tool_prompt_added- ):- self._inject_tool_prompt()-# Add user input to memoryself.update_memory(input_message, OpenAIBackendRole.USER)- try:- return self._handle_step(response_format, self.single_iteration)- finally:- if model_response_format_modified:- # Reset model config back to original state- self.model_backend.model_config_dict = self.original_model_dict-- def _inject_tool_prompt(self) -> None:- r"""Generate and add the tool prompt to memory."""- tool_prompt = self._generate_tool_prompt(- self.model_backend.model_config_dict["tools"]- )- tool_msg = BaseMessage.make_assistant_message(- role_name="Assistant", content=tool_prompt- )- self.update_memory(tool_msg, OpenAIBackendRole.SYSTEM)- self.tool_prompt_added = True-- def _handle_step(- self,- response_format: Optional[Type[BaseModel]],- single_step: bool,- ) -> ChatAgentResponse:- r"""Handles a single or multi-step interaction."""-- if (- self.model_backend.model_config_dict.get("tool_choice")- == "required"- and not single_step- ):- raise ValueError(- "`tool_choice` cannot be set to `required` for multi-step"- " mode. To proceed, set `single_iteration` to `True`."- )-- # Record function calls made during the sessiontool_call_records: List[ToolCallingRecord] = []-- external_tool_request = None+ external_tool_call_request: Optional[ToolCallRequest] = Nonewhile True:try:openai_messages, num_tokens = self.memory.get_context()except RuntimeError as e:- self.model_backend.model_config_dict = self.original_model_dictreturn self._step_token_exceed(e.args[1], tool_call_records, "max_tokens_exceeded")-- # Prompt engineering approach for structured output for non-native tool calling models- inject_prompt_for_structured_output = (- response_format- and not self.model_type.support_native_structured_output- )-- if inject_prompt_for_structured_output:- # update last openai message- usr_msg = openai_messages.pop()- usr_msg["content"] = generate_prompt_for_structured_output(- response_format,- usr_msg["content"], # type: ignore [arg-type]- )- openai_messages.append(usr_msg)-- # Process model response- (- response,- output_messages,- finish_reasons,- usage_dict,- response_id,- ) = self._step_model_response(openai_messages, num_tokens)-- # Try to parse structured output to return a Pydantic object- if inject_prompt_for_structured_output and isinstance(- response, ChatCompletion- ):- content = response.choices[0].message.content- try:- json_content = json.loads(str(content))- output_messages[0].parsed = response_format(**json_content) # type: ignore [assignment, misc]- except json.JSONDecodeError as e:- logger.error(- f"Failed in parsing the output into JSON: {e}"- )- output_messages[0].parsed = None- except ValidationError as e:- logger.warning(- "Successfully generating JSON response, "- "but failed in parsing it into Pydantic object :"- f"{e}, return the JSON response in parsed field"- )- output_messages[0].parsed = json_content-- # Finalize on standard response in multi-step mode- if self._is_standard_response(response):- break-- # Handle tool requests- tool_request = self._extract_tool_call(response)- if isinstance(response, ChatCompletion) and tool_request:- response.choices[0].message.tool_calls = [tool_request]- tool_call_records.append(- self._step_tool_call_and_update(response)- )-- if tool_request.function.name in self.external_tool_names:- external_tool_request = tool_request- info = self._step_get_info(- output_messages,- finish_reasons,- usage_dict,- response_id,- tool_call_records,- num_tokens,- tool_request,- )- self._log_final_output(output_messages)- self.model_backend.model_config_dict = (- self.original_model_dict- )- return ChatAgentResponse(- msgs=output_messages,- terminated=self.terminated,- info=info,- )-- # Single-step mode ends after one iteration- if single_step:- break-- # Optional structured output via function calling- if (- response_format- and not inject_prompt_for_structured_output- and self.model_type- not in {- "gpt-4o",- "gpt-4o-mini",- }- ):- (- output_messages,- finish_reasons,- usage_dict,- response_id,- tool_call,+ # Get response from model backend+ response = self._get_model_response(+ openai_messages,num_tokens,- ) = self._structure_output_with_function(response_format)- tool_call_records.append(tool_call)-- # Final info and response- info = self._step_get_info(- output_messages,- finish_reasons,- usage_dict,- response_id,- tool_call_records,- num_tokens,- external_tool_request,- )- self._log_final_output(output_messages)- self.model_backend.model_config_dict = self.original_model_dict- return ChatAgentResponse(- msgs=output_messages, terminated=self.terminated, info=info- )-- def _extract_tool_call(- self, response: Any- ) -> Optional[ChatCompletionMessageToolCall]:- 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.- """- # Check if the response contains tool calls- if (- self.is_tools_added()- and not self.model_type.support_native_tool_calling- and "</function>" in response.choices[0].message.content- ):- parsed_content = self._parse_tool_response(- response.choices[0].message.content+ response_format,+ self._get_full_tool_schemas(),)- 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.is_tools_added()- 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+ if self.single_iteration:+ break- def _is_standard_response(self, response: Any) -> bool:- r"""Determine if the provided response is a standard reply without- tool calls.+ if tool_call_request := response.tool_call_request:+ if tool_call_request.tool_name in self._external_tool_schemas:+ external_tool_call_request = tool_call_request+ break- Args:- response (Any): The response object to evaluate.+ tool_call_records.append(self._execute_tool(tool_call_request))+ continue- Returns:- bool: `True` if the response is a standard reply, `False`- otherwise.- """- if not self.is_tools_added():- return True+ break- if not isinstance(response, ChatCompletion):- return True+ self._format_response_if_needed(response, response_format)+ self._record_final_output(response.output_messages)- if self.model_type.support_native_tool_calling:- return not response.choices[0].message.tool_calls-- return "</function>" not in str(- response.choices[0].message.content or ""+ return self._convert_to_chatagent_response(+ response, tool_call_records, num_tokens, external_tool_call_request)- def _log_final_output(self, output_messages: List[BaseMessage]) -> None:- r"""Log final messages or warnings about multiple responses."""- if len(output_messages) == 1:- self.record_message(output_messages[0])- else:- logger.warning(- "Multiple messages returned in `step()`. Record "- "selected message manually using `record_message()`."- )+ @property+ def chat_history(self) -> List[OpenAIMessage]:+ openai_messages, _ = self.memory.get_context()+ return openai_messages- async def step_async(+ async def astep(self,input_message: Union[BaseMessage, str],response_format: Optional[Type[BaseModel]] = None,@@ -879,12 +544,13 @@ class ChatAgent(BaseAgent):"""if isinstance(input_message, str):input_message = BaseMessage.make_user_message(- role_name='User', content=input_message+ role_name="User", content=input_message)self.update_memory(input_message, OpenAIBackendRole.USER)tool_call_records: List[ToolCallingRecord] = []+ external_tool_call_request: Optional[ToolCallRequest] = Nonewhile True:try:openai_messages, num_tokens = self.memory.get_context()@@ -893,219 +559,127 @@ class ChatAgent(BaseAgent):e.args[1], tool_call_records, "max_tokens_exceeded")- (- response,- output_messages,- finish_reasons,- usage_dict,- response_id,- ) = self._step_model_response(openai_messages, num_tokens)-- if (- not self.is_tools_added()- or not isinstance(response, ChatCompletion)- or not response.choices[0].message.tool_calls- ):+ response = await self._aget_model_response(+ openai_messages,+ num_tokens,+ response_format,+ self._get_full_tool_schemas(),+ )++ if self.single_iteration:break- # Check for external tool call- external_tool_request = response.choices[0].message.tool_calls[0]- if external_tool_request.function.name in self.external_tool_names:- # if model calls an external tool, directly return the request- info = self._step_get_info(- output_messages,- finish_reasons,- usage_dict,- response_id,- tool_call_records,- num_tokens,- external_tool_request,- )- return ChatAgentResponse(- msgs=output_messages, terminated=self.terminated, info=info- )+ if tool_call_request := response.tool_call_request:+ if tool_call_request.tool_name in self._external_tool_schemas:+ external_tool_call_request = tool_call_request+ break- # Normal function calling- tool_call_records.append(- await self._step_tool_call_and_update_async(response)- )+ tool_call_record = await self._aexecute_tool(tool_call_request)+ tool_call_records.append(tool_call_record)+ continue- if (- response_format is not None- and self.model_type.support_native_tool_calling- ):- (- output_messages,- finish_reasons,- usage_dict,- response_id,- tool_call_record,- num_tokens,- ) = self._structure_output_with_function(response_format)- tool_call_records.append(tool_call_record)+ break++ await self._aformat_response_if_needed(response, response_format)+ self._record_final_output(response.output_messages)++ return self._convert_to_chatagent_response(+ response, tool_call_records, num_tokens, external_tool_call_request+ )+ def _convert_to_chatagent_response(+ self,+ response: ModelResponse,+ tool_call_records: List[ToolCallingRecord],+ num_tokens: int,+ external_tool_call_request: Optional[ToolCallRequest],+ ) -> ChatAgentResponse:+ r"""Parse the final model response into the chat agent response."""info = self._step_get_info(- output_messages,- finish_reasons,- usage_dict,- response_id,+ response.output_messages,+ response.finish_reasons,+ response.usage_dict,+ response.response_id,tool_call_records,num_tokens,+ external_tool_call_request,+ )++ return ChatAgentResponse(+ msgs=response.output_messages,+ terminated=self.terminated,+ info=info,)+ def _record_final_output(self, output_messages: List[BaseMessage]) -> None:+ r"""Log final messages or warnings about multiple responses."""if len(output_messages) == 1:- # Auto record if the output result is a single messageself.record_message(output_messages[0])else:logger.warning(- "Multiple messages returned in `step()`, message won't be "- "recorded automatically. Please call `record_message()` to "- "record the selected message manually."+ "Multiple messages returned in `step()`. Record "+ "selected message manually using `record_message()`.")- return ChatAgentResponse(- msgs=output_messages, terminated=self.terminated, info=info- )-- def _step_tool_call_and_update(- self, response: ChatCompletion- ) -> ToolCallingRecord:- r"""Processes a function call within the chat completion response,- records the function call in the provided list of tool calls and- updates the memory of the current agent.-- Args:- response (ChatCompletion): The response object from the chat- completion.+ def _get_model_response(+ self,+ openai_messages: List[OpenAIMessage],+ num_tokens: int,+ response_format: Optional[Type[BaseModel]] = None,+ tool_schemas: Optional[List[Dict[str, Any]]] = None,+ ) -> ModelResponse:+ r"""Internal function for agent step model response."""- Returns:- ToolCallingRecord: The record of calling the function.- """+ response = None+ try:+ response = self.model_backend.run(+ openai_messages, response_format, tool_schemas or None+ )+ except Exception as exc:+ logger.error(+ f"An error occurred while running model "+ f"{self.model_backend.model_type}, "+ f"index: {self.model_backend.current_model_index}",+ exc_info=exc,+ )+ if not response:+ raise ModelProcessingError(+ "Unable to process messages: none of the provided models "+ "run succesfully."+ )- # Perform function calling- func_assistant_msg, func_result_msg, tool_call_record = (- self._step_tool_call(response)+ logger.info(+ f"Model {self.model_backend.model_type}, "+ f"index {self.model_backend.current_model_index}, "+ f"processed these messages: {openai_messages}")- # Update the messages- self.update_memory(func_assistant_msg, OpenAIBackendRole.ASSISTANT)- self.update_memory(func_result_msg, OpenAIBackendRole.FUNCTION)-- return tool_call_record-- async def _step_tool_call_and_update_async(- self, response: ChatCompletion- ) -> ToolCallingRecord:- (- func_assistant_msg,- func_result_msg,- func_record,- ) = await self.step_tool_call_async(response)-- self.update_memory(func_assistant_msg, OpenAIBackendRole.ASSISTANT)- self.update_memory(func_result_msg, OpenAIBackendRole.FUNCTION)-- return func_record-- def _structure_output_with_function(- self, response_format: Type[BaseModel]- ) -> Tuple[- List[BaseMessage],- List[str],- Dict[str, int],- str,- ToolCallingRecord,- int,- ]:- r"""Internal function of structuring the output of the agent based on- the given output schema.-- Args:- response_format (Type[BaseModel]): The output schema to use for- structuring the output.-- Returns:- Tuple[List[BaseMessage], List[str], Dict[str, int], str,- ToolCallingRecord, int]:- A tuple containing the output messages, finish reasons, usage- dictionary, response ID, function calling record, and number of- tokens.- """- from camel.toolkits import FunctionTool-- schema_json = get_pydantic_object_schema(response_format)- func_str = json_to_function_code(schema_json)- func_callable = func_string_to_callable(func_str)- func = FunctionTool(func_callable)-- original_model_dict = self.model_backend.model_config_dict-- # Replace the original tools with the structuring function- self.tool_dict = {func.get_function_name(): func}- self.model_backend.model_config_dict = original_model_dict.copy()- self.model_backend.model_config_dict["tools"] = [- func.get_openai_tool_schema()- ]- self.model_backend.model_config_dict["tool_choice"] = "required"-- openai_messages, num_tokens = self.memory.get_context()- (- response,- output_messages,- finish_reasons,- usage_dict,- response_id,- ) = self._step_model_response(openai_messages, num_tokens)-if isinstance(response, ChatCompletion):- tool_call_record = self._step_tool_call_and_update(response)+ return self._handle_batch_response(response)else:- raise ValueError(- "Structured output is not supported for stream responses."- )-- for base_message_item in output_messages:- base_message_item.content = json.dumps(tool_call_record.result)+ return self._handle_stream_response(response, num_tokens)- # Recover the original tools- self.model_backend.model_config_dict = original_model_dict-- return (- output_messages,- finish_reasons,- usage_dict,- response_id,- tool_call_record,- num_tokens,- )-- def _step_model_response(+ async def _aget_model_response(self,openai_messages: List[OpenAIMessage],num_tokens: int,- ) -> tuple[- Union[ChatCompletion, Stream],- List[BaseMessage],- List[str],- Dict[str, int],- str,- ]:+ response_format: Optional[Type[BaseModel]] = None,+ tool_schemas: Optional[List[Dict[str, Any]]] = None,+ ) -> ModelResponse:r"""Internal function for agent step model response."""response = None- # Obtain the model's response- for _ in range(len(self.model_backend.models)):- try:- response = self.model_backend.run(openai_messages)- break- except Exception as exc:- logger.error(- f"An error occurred while running model "- f"{self.model_backend.model_type}, "- f"index: {self.model_backend.current_model_index}",- exc_info=exc,- )- continue+ try:+ response = await self.model_backend.arun(+ openai_messages, response_format, tool_schemas or None+ )+ except Exception as exc:+ logger.error(+ f"An error occurred while running model "+ f"{self.model_backend.model_type}, "+ f"index: {self.model_backend.current_model_index}",+ exc_info=exc,+ )if not response:raise ModelProcessingError("Unable to process messages: none of the provided models "@@ -1119,20 +693,9 @@ class ChatAgent(BaseAgent):)if isinstance(response, ChatCompletion):- output_messages, finish_reasons, usage_dict, response_id = (- self.handle_batch_response(response)- )+ return self._handle_batch_response(response)else:- output_messages, finish_reasons, usage_dict, response_id = (- self.handle_stream_response(response, num_tokens)- )- return (- response,- output_messages,- finish_reasons,- usage_dict,- response_id,- )+ return await self._ahandle_stream_response(response, num_tokens)def _step_get_info(self,@@ -1142,7 +705,7 @@ class ChatAgent(BaseAgent):response_id: str,tool_calls: List[ToolCallingRecord],num_tokens: int,- external_tool_request: Optional[ChatCompletionMessageToolCall] = None,+ external_tool_call_request: Optional[ToolCallRequest] = None,) -> Dict[str, Any]:r"""Process the output of a chat step and gather information about thestep.@@ -1162,9 +725,8 @@ class ChatAgent(BaseAgent):tool_calls (List[ToolCallingRecord]): Records of function callsmade during this step.num_tokens (int): The number of tokens used in this step.- external_tool_request (Optional[ChatCompletionMessageToolCall]):- Any external tool request made during this step.- (default: :obj:`None`)+ external_tool_call_request (Optional[ToolCallRequest]): The+ request for external tool call.Returns:Dict[str, Any]: A dictionary containing information about the chat@@ -1194,103 +756,114 @@ class ChatAgent(BaseAgent):if self.terminated and termination_reason is not None:finish_reasons = [termination_reason] * len(finish_reasons)- info = self.get_info(+ return get_info_dict(response_id,usage_dict,finish_reasons,num_tokens,tool_calls,- external_tool_request,+ external_tool_call_request,)- return info- def handle_batch_response(+ def _handle_batch_response(self, response: ChatCompletion- ) -> Tuple[List[BaseMessage], List[str], Dict[str, int], str]:+ ) -> ModelResponse:r"""Process a batch response from the model and extract the necessaryinformation.Args:- response (dict): Model response.+ response (ChatCompletion): Model response.Returns:- tuple: A tuple of list of output `ChatMessage`, list of- finish reasons, usage dictionary, and response id.+ _ModelResponse: parsed model response."""output_messages: List[BaseMessage] = []for choice in response.choices:+ meta_dict = {}+ if logprobs_info := handle_logprobs(choice):+ meta_dict["logprobs_info"] = logprobs_info+chat_message = BaseMessage(role_name=self.role_name,role_type=self.role_type,- meta_dict=dict(),+ meta_dict=meta_dict,content=choice.message.content or "",- parsed=getattr(choice.message, 'parsed', None),+ parsed=getattr(choice.message, "parsed", None),)- # Process log probabilities and append to the message meta information- if choice.logprobs is not None:- tokens_logprobs = choice.logprobs.content-- if tokens_logprobs is not None:- # Extract and structure logprob information- logprobs_info = [- {- "token": token_logprob.token,- "logprob": token_logprob.logprob,- "top_logprobs": [- (top_logprob.token, top_logprob.logprob)- for top_logprob in token_logprob.top_logprobs- ],- }- for token_logprob in tokens_logprobs- ]- # Ensure meta_dict exists before adding logprobs info- if chat_message.meta_dict is None:- chat_message.meta_dict = {}- chat_message.meta_dict["logprobs_info"] = logprobs_info- # Append the processed chat message to output+output_messages.append(chat_message)finish_reasons = [str(choice.finish_reason) for choice in response.choices]- usage = (- self._safe_model_dump(response.usage)- if response.usage is not None- else {}- )- return (- output_messages,- finish_reasons,- usage,- response.id,- )- def _safe_model_dump(self, obj) -> dict:- r"""Safely dump a Pydantic model to a dictionary.+ usage = {}+ if response.usage is not None:+ usage = safe_model_dump(response.usage)++ tool_call_request: Optional[ToolCallRequest] = None+ if tool_calls := response.choices[0].message.tool_calls:+ tool_name = tool_calls[0].function.name+ tool_call_id = tool_calls[0].id+ args = json.loads(tool_calls[0].function.arguments)+ tool_call_request = ToolCallRequest(+ tool_name=tool_name, args=args, tool_call_id=tool_call_id+ )- This method attempts to use the `model_dump` method if available,- otherwise it falls back to the `dict` method.+ return ModelResponse(+ response=response,+ tool_call_request=tool_call_request,+ output_messages=output_messages,+ finish_reasons=finish_reasons,+ usage_dict=usage,+ response_id=response.id or "",+ )++ def _handle_stream_response(+ self,+ response: Stream[ChatCompletionChunk],+ prompt_tokens: int,+ ) -> ModelResponse:+ r"""Process a stream response from the model and extract the necessary+ information.Args:- obj: The Pydantic model instance to be dumped.+ response (dict): Model response.+ prompt_tokens (int): Number of input prompt tokens.Returns:- dict: A dictionary representation of the Pydantic model.+ _ModelResponse: a parsed model response."""- # Check if the `model_dump` method exists (Pydantic v2)- if hasattr(obj, 'model_dump'):- return obj.model_dump()- # Fallback to `dict()` method (Pydantic v1)- elif hasattr(obj, 'dict'):- return obj.dict()- else:- raise TypeError("The object is not a Pydantic model")+ content_dict: defaultdict = defaultdict(lambda: "")+ finish_reasons_dict: defaultdict = defaultdict(lambda: "")+ output_messages: List[BaseMessage] = []+ response_id: str = ""+ # All choices in one response share one role+ for chunk in response:+ response_id = chunk.id+ self._handle_chunk(+ chunk, content_dict, finish_reasons_dict, output_messages+ )+ finish_reasons = [+ finish_reasons_dict[i] for i in range(len(finish_reasons_dict))+ ]+ usage_dict = self.get_usage_dict(output_messages, prompt_tokens)++ # TODO: Handle tool calls+ return ModelResponse(+ response=response,+ tool_call_request=None,+ output_messages=output_messages,+ finish_reasons=finish_reasons,+ usage_dict=usage_dict,+ response_id=response_id,+ )- def handle_stream_response(+ async def _ahandle_stream_response(self,- response: Stream[ChatCompletionChunk],+ response: AsyncStream[ChatCompletionChunk],prompt_tokens: int,- ) -> Tuple[List[BaseMessage], List[str], Dict[str, int], str]:+ ) -> ModelResponse:r"""Process a stream response from the model and extract the necessaryinformation.@@ -1299,37 +872,58 @@ class ChatAgent(BaseAgent):prompt_tokens (int): Number of input prompt tokens.Returns:- tuple: A tuple of list of output `ChatMessage`, list of- finish reasons, usage dictionary, and response id.+ _ModelResponse: a parsed model response."""content_dict: defaultdict = defaultdict(lambda: "")finish_reasons_dict: defaultdict = defaultdict(lambda: "")output_messages: List[BaseMessage] = []response_id: str = ""# All choices in one response share one role- for chunk in response:+ async for chunk in response:response_id = chunk.id- for choice in chunk.choices:- index = choice.index- delta = choice.delta- if delta.content is not None:- # When response has not been stopped- # Notice that only the first chunk_dict has the "role"- content_dict[index] += delta.content- if choice.finish_reason:- finish_reasons_dict[index] = choice.finish_reason- chat_message = BaseMessage(- role_name=self.role_name,- role_type=self.role_type,- meta_dict=dict(),- content=content_dict[index],- )- output_messages.append(chat_message)+ self._handle_chunk(+ chunk, content_dict, finish_reasons_dict, output_messages+ )finish_reasons = [finish_reasons_dict[i] for i in range(len(finish_reasons_dict))]usage_dict = self.get_usage_dict(output_messages, prompt_tokens)- return output_messages, finish_reasons, usage_dict, response_id++ # TODO: Handle tool calls+ return ModelResponse(+ response=response,+ tool_call_request=None,+ output_messages=output_messages,+ finish_reasons=finish_reasons,+ usage_dict=usage_dict,+ response_id=response_id,+ )++ def _handle_chunk(+ self,+ chunk: ChatCompletionChunk,+ content_dict: defaultdict,+ finish_reasons_dict: defaultdict,+ output_messages: List[BaseMessage],+ ) -> None:+ r"""Handle a chunk of the model response."""+ for choice in chunk.choices:+ index = choice.index+ delta = choice.delta+ if delta.content is not None:+ content_dict[index] += delta.content++ if not choice.finish_reason:+ continue++ finish_reasons_dict[index] = choice.finish_reason+ chat_message = BaseMessage(+ role_name=self.role_name,+ role_type=self.role_type,+ meta_dict=dict(),+ content=content_dict[index],+ )+ output_messages.append(chat_message)def _step_token_exceed(self,@@ -1351,9 +945,8 @@ class ChatAgent(BaseAgent):information about token number and called functions."""self.terminated = True- output_messages: List[BaseMessage] = []- info = self.get_info(+ info = get_info_dict(None,None,[termination_reason],@@ -1362,111 +955,53 @@ class ChatAgent(BaseAgent):)return ChatAgentResponse(- msgs=output_messages,+ msgs=[],terminated=self.terminated,info=info,)- def _step_tool_call(+ def _execute_tool(self,- response: ChatCompletion,- ) -> Tuple[- FunctionCallingMessage, FunctionCallingMessage, ToolCallingRecord- ]:- r"""Execute the function with arguments following the model's response.+ tool_call_request: ToolCallRequest,+ ) -> ToolCallingRecord:+ r"""Execute the tool with arguments following the model's response.Args:- response (Dict[str, Any]): The response obtained by calling the- model.+ tool_call_request (_ToolCallRequest): The tool call request.Returns:- tuple: A tuple consisting of two obj:`FunctionCallingMessage`,- one about the arguments and the other about the execution- result, and a struct for logging information about this+ FunctionCallingRecord: A struct for logging information about thisfunction call."""- choice = response.choices[0]- if choice.message.tool_calls is None:- raise RuntimeError("Tool call is None")- func_name = choice.message.tool_calls[0].function.name-- arguments_str = choice.message.tool_calls[0].function.arguments- args = self._safe_json_loads(arguments_str)-- tool = self.tool_dict[func_name]+ func_name = tool_call_request.tool_name+ args = tool_call_request.args+ tool_call_id = tool_call_request.tool_call_id+ tool = self._internal_tools[func_name]result = tool(**args)- tool_call_id = choice.message.tool_calls[0].id- assist_msg = FunctionCallingMessage(- role_name=self.role_name,- role_type=self.role_type,- meta_dict=None,- content="",- func_name=func_name,- args=args,- tool_call_id=tool_call_id,- )- func_msg = FunctionCallingMessage(- role_name=self.role_name,- role_type=self.role_type,- meta_dict=None,- content="",- func_name=func_name,- result=result,- tool_call_id=tool_call_id,- )-- # Record information about this function call- func_record = ToolCallingRecord(- tool_name=func_name,- args=args,- result=result,- tool_call_id=tool_call_id,- )- return assist_msg, func_msg, func_record-- def _safe_json_loads(self, arguments_str):- # Replace Python types with their JSON equivalents- arguments_str = arguments_str.replace("None", "null")- arguments_str = arguments_str.replace("True", "true")- arguments_str = arguments_str.replace("False", "false")-- # Attempt to parse the corrected string- try:- return json.loads(arguments_str)- except json.JSONDecodeError as e:- raise ValueError(f"Invalid JSON format: {e}")+ return self._record_tool_calling(func_name, args, result, tool_call_id)- async def step_tool_call_async(+ async def _aexecute_tool(self,- response: ChatCompletion,- ) -> Tuple[- FunctionCallingMessage, FunctionCallingMessage, ToolCallingRecord- ]:- r"""Execute the async function with arguments following the model's- response.-- Args:- response (Dict[str, Any]): The response obtained by calling the- model.-- Returns:- tuple: A tuple consisting of two obj:`FunctionCallingMessage`,- one about the arguments and the other about the execution- result, and a struct for logging information about this- function call.+ tool_call_request: ToolCallRequest,+ ) -> ToolCallingRecord:+ func_name = tool_call_request.tool_name+ args = tool_call_request.args+ tool_call_id = tool_call_request.tool_call_id+ tool = self._internal_tools[func_name]+ result = await tool.async_call(**args)+ return self._record_tool_calling(func_name, args, result, tool_call_id)++ def _record_tool_calling(+ self,+ func_name: str,+ args: Dict[str, Any],+ result: Any,+ tool_call_id: str,+ ):+ r"""Record the tool calling information in the memory, and return the+ tool calling record."""- # Note that when function calling is enabled, `n` is set to 1.- choice = response.choices[0]- if choice.message.tool_calls is None:- raise RuntimeError("Tool call is None")- func_name = choice.message.tool_calls[0].function.name-- args = json.loads(choice.message.tool_calls[0].function.arguments)- tool = self.tool_dict[func_name]- result = await tool(**args)- tool_call_id = choice.message.tool_calls[0].id-assist_msg = FunctionCallingMessage(role_name=self.role_name,role_type=self.role_type,@@ -1486,14 +1021,18 @@ class ChatAgent(BaseAgent):tool_call_id=tool_call_id,)- # Record information about this function call- func_record = ToolCallingRecord(+ self.update_memory(assist_msg, OpenAIBackendRole.ASSISTANT)+ self.update_memory(func_msg, OpenAIBackendRole.FUNCTION)++ # Record information about this tool call+ tool_record = ToolCallingRecord(tool_name=func_name,args=args,result=result,tool_call_id=tool_call_id,)- return assist_msg, func_msg, func_record++ return tool_recorddef get_usage_dict(self, output_messages: List[BaseMessage], prompt_tokens: int@@ -1508,15 +1047,15 @@ class ChatAgent(BaseAgent):dict: Usage dictionary."""encoding = get_model_encoding(self.model_type.value_for_tiktoken)- completion_tokens = 0- for message in output_messages:- completion_tokens += len(encoding.encode(message.content))- usage_dict = dict(+ completion_tokens = sum(+ len(encoding.encode(message.content))+ for message in output_messages+ )+ return dict(completion_tokens=completion_tokens,prompt_tokens=prompt_tokens,total_tokens=completion_tokens + prompt_tokens,)- return usage_dictdef add_model_scheduling_strategy(self, name: str, strategy_fn: Callable):r"""Add a scheduling strategy method provided by user to ModelManger.diff --git a/camel/agents/multi_hop_generator_agent.py b/camel/agents/multi_hop_generator_agent.pyindex 988342b9a..bcdcdca28 100644--- a/camel/agents/multi_hop_generator_agent.py+++ b/camel/agents/multi_hop_generator_agent.py@@ -75,7 +75,7 @@ class MultiHopGeneratorAgent(ProgrammableChatAgent):Supporting Facts: [List of relevant text segments used]""" # noqa: E501)- self.system_message = BaseMessage.make_assistant_message(+ self._system_message = BaseMessage.make_assistant_message(role_name='Assistant', content=system_text)diff --git a/camel/configs/base_config.py b/camel/configs/base_config.pyindex 5a6e74819..bd15ec90b 100644--- a/camel/configs/base_config.py+++ b/camel/configs/base_config.py@@ -66,6 +66,8 @@ class BaseConfig(ABC, BaseModel):This method converts the current configuration object to a dictionaryrepresentation, which can be used for serialization or other purposes.+ The dictionary won't contain None values, as some API does not support+ None values. (Like tool in OpenAI beta API)Returns:dict[str, Any]: A dictionary representation of the current@@ -73,17 +75,12 @@ class BaseConfig(ABC, BaseModel):"""config_dict = self.model_dump()- tools_schema = None- if self.tools:- from camel.toolkits import FunctionTool+ # Convert tools to OpenAI tool schema+ config_dict["tools"] = (+ [tool.get_openai_tool_schema() for tool in self.tools]+ if self.tools+ else None+ )- tools_schema = []- for tool in self.tools:- if not isinstance(tool, FunctionTool):- raise ValueError(- f"The tool {tool} should "- "be an instance of `FunctionTool`."- )- tools_schema.append(tool.get_openai_tool_schema())- config_dict["tools"] = tools_schema- return config_dict+ # Remove None values+ return {k: v for k, v in config_dict.items() if v is not None}diff --git a/camel/configs/deepseek_config.py b/camel/configs/deepseek_config.pyindex 4bf8eb7b4..e0bb15724 100644--- a/camel/configs/deepseek_config.py+++ b/camel/configs/deepseek_config.py@@ -14,12 +14,11 @@from __future__ import annotations-from typing import Any, Optional, Sequence, Type, Union+from typing import Optional, Sequence, Type, Unionfrom pydantic import BaseModelfrom camel.configs.base_config import BaseConfig-from camel.types import NOT_GIVEN, NotGivenclass DeepSeekConfig(BaseConfig):@@ -89,10 +88,10 @@ class DeepSeekConfig(BaseConfig):temperature: float = 1.0 # deepseek default: 1.0top_p: float = 1.0stream: bool = False- stop: Union[str, Sequence[str], NotGiven] = NOT_GIVEN- max_tokens: Union[int, NotGiven] = NOT_GIVEN+ stop: Optional[Union[str, Sequence[str]]] = None+ max_tokens: Optional[int] = Nonepresence_penalty: float = 0.0- response_format: Union[Type[BaseModel], dict, NotGiven] = NOT_GIVEN+ response_format: Optional[Union[Type[BaseModel], dict]] = Nonefrequency_penalty: float = 0.0tool_choice: Optional[Union[dict[str, str], str]] = Nonelogprobs: bool = False@@ -105,30 +104,5 @@ class DeepSeekConfig(BaseConfig):if self.stream:self.stream_options = {"include_usage": include_usage}- def as_dict(self) -> dict[str, Any]:- r"""Convert the current configuration to a dictionary.-- This method converts the current configuration object to a dictionary- representation, which can be used for serialization or other purposes.-- Returns:- dict[str, Any]: A dictionary representation of the current- configuration.- """- config_dict = self.model_dump()- if self.tools:- from camel.toolkits import FunctionTool-- tools_schema = []- for tool in self.tools:- if not isinstance(tool, FunctionTool):- raise ValueError(- f"The tool {tool} should "- "be an instance of `FunctionTool`."- )- tools_schema.append(tool.get_openai_tool_schema())- config_dict["tools"] = NOT_GIVEN- return config_dict-DEEPSEEK_API_PARAMS = {param for param in DeepSeekConfig.model_fields.keys()}diff --git a/camel/configs/gemini_config.py b/camel/configs/gemini_config.pyindex 14d39aee1..2ac5bbe2a 100644--- a/camel/configs/gemini_config.py+++ b/camel/configs/gemini_config.py@@ -14,12 +14,11 @@from __future__ import annotations-from typing import Any, Optional, Sequence, Type, Union+from typing import Optional, Sequence, Type, Unionfrom pydantic import BaseModelfrom camel.configs.base_config import BaseConfig-from camel.types import NOT_GIVEN, NotGivenclass GeminiConfig(BaseConfig):@@ -80,35 +79,10 @@ class GeminiConfig(BaseConfig):top_p: float = 1.0n: int = 1stream: bool = False- stop: Union[str, Sequence[str], NotGiven] = NOT_GIVEN- max_tokens: Union[int, NotGiven] = NOT_GIVEN- response_format: Union[Type[BaseModel], dict, NotGiven] = NOT_GIVEN- tool_choice: Optional[Union[dict[str, str], str, NotGiven]] = NOT_GIVEN-- def as_dict(self) -> dict[str, Any]:- r"""Convert the current configuration to a dictionary.-- This method converts the current configuration object to a dictionary- representation, which can be used for serialization or other purposes.-- Returns:- dict[str, Any]: A dictionary representation of the current- configuration.- """- config_dict = self.model_dump()- if self.tools:- from camel.toolkits import FunctionTool-- tools_schema = []- for tool in self.tools:- if not isinstance(tool, FunctionTool):- raise ValueError(- f"The tool {tool} should "- "be an instance of `FunctionTool`."- )- tools_schema.append(tool.get_openai_tool_schema())- config_dict["tools"] = NOT_GIVEN- return config_dict+ stop: Optional[Union[str, Sequence[str]]] = None+ max_tokens: Optional[int] = None+ response_format: Optional[Union[Type[BaseModel], dict]] = None+ tool_choice: Optional[Union[dict[str, str], str]] = NoneGemini_API_PARAMS = {param for param in GeminiConfig.model_fields.keys()}diff --git a/camel/configs/openai_config.py b/camel/configs/openai_config.pyindex 71b66ac97..8ee7fdca0 100644--- a/camel/configs/openai_config.py+++ b/camel/configs/openai_config.py@@ -13,12 +13,11 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========from __future__ import annotations-from typing import Any, Optional, Sequence, Type, Union+from typing import Dict, Optional, Sequence, Type, Unionfrom pydantic import BaseModel, Fieldfrom camel.configs.base_config import BaseConfig-from camel.types import NOT_GIVEN, NotGivenclass ChatGPTConfig(BaseConfig):@@ -101,39 +100,14 @@ class ChatGPTConfig(BaseConfig):top_p: float = 1.0n: int = 1stream: bool = False- stop: Union[str, Sequence[str], NotGiven] = NOT_GIVEN- max_tokens: Union[int, NotGiven] = NOT_GIVEN+ stop: Optional[Union[str, Sequence[str]]] = None+ max_tokens: Optional[int] = Nonepresence_penalty: float = 0.0- response_format: Union[Type[BaseModel], dict, NotGiven] = NOT_GIVEN+ response_format: Optional[Union[Type[BaseModel], Dict]] = Nonefrequency_penalty: float = 0.0- logit_bias: dict = Field(default_factory=dict)+ logit_bias: Dict = Field(default_factory=dict)user: str = ""- tool_choice: Optional[Union[dict[str, str], str]] = None-- def as_dict(self) -> dict[str, Any]:- r"""Convert the current configuration to a dictionary.-- This method converts the current configuration object to a dictionary- representation, which can be used for serialization or other purposes.-- Returns:- dict[str, Any]: A dictionary representation of the current- configuration.- """- config_dict = self.model_dump()- if self.tools:- from camel.toolkits import FunctionTool-- tools_schema = []- for tool in self.tools:- if not isinstance(tool, FunctionTool):- raise ValueError(- f"The tool {tool} should "- "be an instance of `FunctionTool`."- )- tools_schema.append(tool.get_openai_tool_schema())- config_dict["tools"] = NOT_GIVEN- return config_dict+ tool_choice: Optional[Union[Dict[str, str], str]] = NoneOPENAI_API_PARAMS = {param for param in ChatGPTConfig.model_fields.keys()}diff --git a/camel/configs/qwen_config.py b/camel/configs/qwen_config.pyindex 91a962a78..646174c04 100644--- a/camel/configs/qwen_config.py+++ b/camel/configs/qwen_config.py@@ -13,10 +13,9 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========from __future__ import annotations-from typing import ClassVar, Optional, Union+from typing import Dict, List, Optional, Unionfrom camel.configs.base_config import BaseConfig-from camel.types import NOT_GIVEN, NotGivenclass QwenConfig(BaseConfig):@@ -27,58 +26,59 @@ class QwenConfig(BaseConfig):Args:stream (bool, optional): Whether to stream the response.(default: :obj:`False`)- temperature (float, optional): Controls the diversity and focus of- the generated results. Lower values make the output more focused,- while higher values make it more diverse. (default: :obj:`0.3`)- top_p (float, optional): Controls the diversity and focus of the- generated results. Higher values make the output more diverse,+ temperature (float, optional): Controls the diversity and+ focus of the generated results. Lower values make the output more+ focused, while higher values make it more diverse.+ (default: :obj:`0.3`)+ top_p (float, optional): Controls the diversity and focus of+ the generated results. Higher values make the output more diverse,while lower values make it more focused. (default: :obj:`0.9`)- presence_penalty (float, optional): Controls the repetition of+ presence_penalty (float, optional): Controls the repetitioncontent in the generated results. Positive values reduce therepetition of content, while negative values increase it.(default: :obj:`0.0`)- response_format (object, optional): Specifies the format of the- returned content. The available values are `{"type": "text"}` or- `{"type": "json_object"}`. Setting it to `{"type": "json_object"}`- will output a standard JSON string.- (default: :obj:`{"type": "text"}`)- max_tokens (Union[int, NotGiven], optional): Allows the model to+ response_format (Optional[Dict[str, str]], optional): Specifies the+ format of the returned content. The available values are+ `{"type": "text"}` or `{"type": "json_object"}`. Setting it to+ `{"type": "json_object"}` will output a standard JSON string.+ (default: :obj:`None`)+ max_tokens (Optional[int], optional): Allows the model togenerate the maximum number of tokens.- (default: :obj:`NOT_GIVEN`)- seed (int, optional): Sets the seed parameter to make the text- generation process more deterministic, typically used to ensure- that the results are consistent across model runs. By passing the- same seed value (specified by you) in each model call while- keeping other parameters unchanged, the model is likely to return- the same result.(default: :obj:`None`)- stop (str or list, optional): Using the stop parameter, the model will- automatically stop generating text when it is about to include the- specified string or token_id. You can use the stop parameter to- control the output of the model by passing sensitive words.+ seed (Optional[int], optional): Sets the seed parameter to make the+ text generation process more deterministic, typically used to+ ensure that the results are consistent across model runs. By+ passing the same seed value (specified by you) in each model call+ while keeping other parameters unchanged, the model is likely to+ return the same result.(default: :obj:`None`)- tools (list, optional): Specifies an array of tools that the model can+ stop (Optional[Union[str, List]], optional): Using the stop parameter,+ the model will automatically stop generating text when it is about+ to include the specified string or token_id. You can use the stop+ parameter to control the output of the model by passing sensitive+ words. (default: :obj:`None`)+ tools (List, optional): Specifies an array of tools that the model cancall. It can contain one or more tool objects. During a functioncall process, the model will select one tool from the array.(default: :obj:`None`)- extra_body (dict, optional): Additional parameters to be sent to the- Qwen API. If you want to enable internet search, you can set this- parameter to `{"enable_search": True}`.- (default: :obj:`{"enable_search": False}`)+ extra_body (Optional[Dict[str, str]], optional): Additional parameters+ to be sent to the Qwen API. If you want to enable internet search,+ you can set this parameter to `{"enable_search": True}`.+ (default: :obj:`None`)include_usage (bool, optional): When streaming, specifies whether to- include usage information in `stream_options`. (default:- :obj:`True`)+ include usage information in `stream_options`.+ (default: :obj:`True`)"""stream: bool = Falsetemperature: float = 0.3top_p: float = 0.9presence_penalty: float = 0.0- response_format: ClassVar[dict] = {"type": "text"}- max_tokens: Union[int, NotGiven] = NOT_GIVEN+ response_format: Optional[Dict[str, str]] = None+ max_tokens: Optional[int] = Noneseed: Optional[int] = None- stop: Optional[Union[str, list]] = None- extra_body: ClassVar[dict] = {"enable_search": False}+ stop: Optional[Union[str, List]] = None+ extra_body: Optional[Dict[str, str]] = Nonedef __init__(self, include_usage: bool = True, **kwargs):super().__init__(**kwargs)diff --git a/camel/messages/base.py b/camel/messages/base.pyindex 2dc754012..70bce9415 100644--- a/camel/messages/base.py+++ b/camel/messages/base.py@@ -15,7 +15,7 @@ import base64import ioimport refrom dataclasses import dataclass-from typing import Any, Dict, List, Literal, Optional, Tuple, Type, Union+from typing import Any, Dict, List, Literal, Optional, Tuple, Unionimport numpy as npfrom PIL import Image@@ -72,7 +72,7 @@ class BaseMessage:image_list: Optional[List[Image.Image]] = Noneimage_detail: Literal["auto", "low", "high"] = "auto"video_detail: Literal["auto", "low", "high"] = "low"- parsed: Optional[Union[Type[BaseModel], dict]] = None+ parsed: Optional[Union[BaseModel, dict]] = None@classmethoddef make_user_message(diff --git a/camel/models/_utils.py b/camel/models/_utils.pynew file mode 100644index 000000000..d727b6b88--- /dev/null+++ b/camel/models/_utils.py@@ -0,0 +1,57 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import textwrap+from typing import Optional, Type++from pydantic import BaseModel++from camel.messages import OpenAIMessage+++def try_modify_message_with_format(+ message: OpenAIMessage,+ response_format: Optional[Type[BaseModel]] = None,+) -> None:+ r"""Modifies the content of the message to include the instruction of using+ the response format.++ The message will not be modified in the following cases:+ - response_format is None+ - message content is not a string+ - message role is assistant++ Args:+ response_format (Optional[Type[BaseModel]]): The Pydantic model class.+ message (OpenAIMessage): The message to be modified.+ """+ if response_format is None:+ return++ if not isinstance(message["content"], str):+ return++ if message["role"] == "assistant":+ return++ json_schema = response_format.model_json_schema()+ updated_prompt = textwrap.dedent(+ f"""\+ {message["content"]}++ 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.+ """ # noqa: E501+ )+ message["content"] = updated_promptdiff --git a/camel/models/aiml_model.py b/camel/models/aiml_model.pyindex 9bc737d9d..64c6c9a42 100644--- a/camel/models/aiml_model.py+++ b/camel/models/aiml_model.py@@ -12,12 +12,14 @@# 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, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import AIML_API_PARAMS, AIMLConfigfrom camel.messages import OpenAIMessage+from camel.models._utils import try_modify_message_with_formatfrom camel.models.base_model import BaseModelBackendfrom camel.types import (ChatCompletion,@@ -81,10 +83,31 @@ class AIMLModel(BaseModelBackend):api_key=self._api_key,base_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )- def run(+ 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+ if response_format:+ try_modify_message_with_format(messages[-1], response_format)+ 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.@@ -97,15 +120,26 @@ class AIMLModel(BaseModelBackend):`ChatCompletion` in the non-stream mode, or`Stream[ChatCompletionChunk]` in the stream mode."""- # Process model configuration parameters- model_config = self.model_config_dict.copy()-- # Handle special case for tools parameter- if model_config.get('tools') is None:- model_config['tools'] = []+ request_config = self._prepare_request(+ messages, response_format, tools+ )response = self._client.chat.completions.create(- messages=messages, model=self.model_type, **model_config+ messages=messages, model=self.model_type, **request_config+ )+ return response++ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ request_config = self._prepare_request(+ messages, response_format, tools+ )+ response = await self._async_client.chat.completions.create(+ messages=messages, model=self.model_type, **request_config)return responsediff --git a/camel/models/anthropic_model.py b/camel/models/anthropic_model.pyindex dee6ec67f..6717d6a64 100644--- a/camel/models/anthropic_model.py+++ b/camel/models/anthropic_model.py@@ -12,7 +12,9 @@# 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, Union++from pydantic import BaseModelfrom camel.configs import ANTHROPIC_API_PARAMS, AnthropicConfigfrom camel.messages import OpenAIMessage@@ -59,7 +61,7 @@ class AnthropicModel(BaseModelBackend):url: Optional[str] = None,token_counter: Optional[BaseTokenCounter] = None,) -> None:- from anthropic import Anthropic+ from anthropic import Anthropic, AsyncAnthropicif model_config_dict is None:model_config_dict = AnthropicConfig().as_dict()@@ -69,6 +71,9 @@ class AnthropicModel(BaseModelBackend):model_type, model_config_dict, api_key, url, token_counter)self.client = Anthropic(api_key=self._api_key, base_url=self._url)+ self.async_client = AsyncAnthropic(+ api_key=self._api_key, base_url=self._url+ )def _convert_response_from_anthropic_to_openai(self, response):# openai ^1.0.0 format, reference openai/types/chat/chat_completion.py@@ -102,9 +107,11 @@ class AnthropicModel(BaseModelBackend):self._token_counter = AnthropicTokenCounter(self.model_type)return self._token_counter- def run(+ def _run(self,messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,):r"""Run inference of Anthropic chat completion.@@ -133,6 +140,37 @@ class AnthropicModel(BaseModelBackend):return response+ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> ChatCompletion:+ r"""Run inference of Anthropic chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ ChatCompletion: Response in the OpenAI API format.+ """+ from anthropic import NOT_GIVEN++ if messages[0]["role"] == "system":+ sys_msg = str(messages.pop(0)["content"])+ else:+ sys_msg = NOT_GIVEN # type: ignore[assignment]+ response = await self.async_client.messages.create(+ model=self.model_type,+ system=sys_msg,+ messages=messages, # type: ignore[arg-type]+ **self.model_config_dict,+ )++ # format response to openai format+ return self._convert_response_from_anthropic_to_openai(response)+def check_model_config(self):r"""Check whether the model configuration is valid for anthropicmodel backends.diff --git a/camel/models/azure_openai_model.py b/camel/models/azure_openai_model.pyindex 1a87b4bea..19a483151 100644--- a/camel/models/azure_openai_model.py+++ b/camel/models/azure_openai_model.py@@ -12,9 +12,10 @@# 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, Union-from openai import AzureOpenAI, Stream+from openai import AsyncAzureOpenAI, AsyncStream, AzureOpenAI, Stream+from pydantic import BaseModelfrom camel.configs import OPENAI_API_PARAMS, ChatGPTConfigfrom camel.messages import OpenAIMessage@@ -95,6 +96,15 @@ class AzureOpenAIModel(BaseModelBackend):max_retries=3,)+ self._async_client = AsyncAzureOpenAI(+ azure_endpoint=str(self._url),+ azure_deployment=self.azure_deployment_name,+ api_version=self.api_version,+ api_key=self._api_key,+ timeout=180,+ max_retries=3,+ )+@propertydef token_counter(self) -> BaseTokenCounter:r"""Initialize the token counter for the model backend.@@ -107,9 +117,11 @@ class AzureOpenAIModel(BaseModelBackend):self._token_counter = OpenAITokenCounter(self.model_type)return self._token_counter- def run(+ 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 Azure OpenAI chat completion.@@ -129,6 +141,30 @@ class AzureOpenAIModel(BaseModelBackend):)return response+ 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 Azure OpenAI chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.azure_deployment_name, # type:ignore[arg-type]+ **self.model_config_dict,+ )+ return response+def check_model_config(self):r"""Check whether the model configuration contains anyunexpected arguments to Azure OpenAI API.diff --git a/camel/models/base_model.py b/camel/models/base_model.pyindex 44ae64720..97955caed 100644--- a/camel/models/base_model.py+++ b/camel/models/base_model.py@@ -14,9 +14,10 @@import abcimport refrom abc import ABC, abstractmethod-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Union-from openai import Stream+from openai import AsyncStream, Stream+from pydantic import BaseModelfrom camel.messages import OpenAIMessagefrom camel.types import (@@ -127,22 +128,82 @@ class BaseModelBackend(ABC, metaclass=ModelBackendMeta):]@abstractmethod+ def _run(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ pass++ @abstractmethod+ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ pass+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 the query to the backend model.Args:messages (List[OpenAIMessage]): Message list with the chat historyin OpenAI API format.+ response_format (Optional[Type[BaseModel]]): The response format+ to use for the model. (default: :obj:`None`)+ tools (Optional[List[Tool]]): The schema of tools to use for the+ model for this request. Will override the tools specified in+ the model configuration (but not change the configuration).+ (default: :obj:`None`)Returns:Union[ChatCompletion, Stream[ChatCompletionChunk]]:`ChatCompletion` in the non-stream mode, or`Stream[ChatCompletionChunk]` in the stream mode."""- pass+ # None -> use default tools+ if tools is None:+ tools = self.model_config_dict.get("tools", None)+ # Empty -> use no tools+ elif not tools:+ tools = None+ return self._run(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 the query to the backend model asynchronously.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.+ response_format (Optional[Type[BaseModel]]): The response format+ to use for the model. (default: :obj:`None`)+ tools (Optional[List[Tool]]): The schema of tools to use for the+ model for this request. Will override the tools specified in+ the model configuration (but not change the configuration).+ (default: :obj:`None`)++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ if tools is None:+ tools = self.model_config_dict.get("tools", None)+ elif not tools:+ tools = None+ return await self._arun(messages, response_format, tools)@abstractmethoddef check_model_config(self):diff --git a/camel/models/cohere_model.py b/camel/models/cohere_model.pyindex a9deea220..6d57a617b 100644--- a/camel/models/cohere_model.py+++ b/camel/models/cohere_model.py@@ -16,7 +16,9 @@ import jsonimport loggingimport osimport uuid-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union++from pydantic import BaseModelif TYPE_CHECKING:from cohere.types import ChatMessageV2, ChatResponse@@ -24,6 +26,7 @@ if TYPE_CHECKING:from camel.configs import COHERE_API_PARAMS, CohereConfigfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackend+from camel.models._utils import try_modify_message_with_formatfrom camel.types import ChatCompletion, ModelTypefrom camel.utils import (BaseTokenCounter,@@ -67,6 +70,7 @@ class CohereModel(BaseModelBackend):model_type, model_config_dict, api_key, url, token_counter)self._client = cohere.ClientV2(api_key=self._api_key)+ self._async_client = cohere.AsyncClientV2(api_key=self._api_key)def _to_openai_response(self, response: 'ChatResponse') -> ChatCompletion:if response.usage and response.usage.tokens:@@ -215,7 +219,30 @@ class CohereModel(BaseModelBackend):)return self._token_counter- def run(self, messages: List[OpenAIMessage]) -> ChatCompletion:+ 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:+ for tool in tools:+ function_dict = tool.get('function', {})+ function_dict.pop("strict", None)+ 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,+ ) -> ChatCompletion:r"""Runs inference of Cohere chat completion.Args:@@ -226,21 +253,71 @@ class CohereModel(BaseModelBackend):"""from cohere.core.api_error import ApiError- cohere_messages = self._to_cohere_chatmessage(messages)+ request_config = self._prepare_request(+ messages, response_format, tools+ )- # Removing 'strict': True from the dictionary for- # cohere client- if self.model_config_dict.get('tools') is not None:- for tool in self.model_config_dict.get('tools', []):- function_dict = tool.get('function', {})- if 'strict' in function_dict:- del function_dict['strict']+ cohere_messages = self._to_cohere_chatmessage(messages)try:response = self._client.chat(messages=cohere_messages,model=self.model_type,- **self.model_config_dict,+ **request_config,+ )+ except ApiError as e:+ logging.error(f"Cohere API Error: {e.status_code}")+ logging.error(f"Error body: {e.body}")+ raise+ except Exception as e:+ logging.error(f"Unexpected error when calling Cohere API: {e!s}")+ raise++ openai_response = self._to_openai_response(response)++ # Add AgentOps LLM Event tracking+ if LLMEvent:+ llm_event = LLMEvent(+ thread_id=openai_response.id,+ prompt=" ".join(+ [message.get("content") for message in messages] # type: ignore[misc]+ ),+ prompt_tokens=openai_response.usage.prompt_tokens, # type: ignore[union-attr]+ completion=openai_response.choices[0].message.content,+ completion_tokens=openai_response.usage.completion_tokens, # type: ignore[union-attr]+ model=self.model_type,+ )+ record(llm_event)++ return openai_response++ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> ChatCompletion:+ r"""Runs inference of Cohere chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.+ Returns:+ ChatCompletion.+ """+ from cohere.core.api_error import ApiError++ request_config = self._prepare_request(+ messages, response_format, tools+ )++ cohere_messages = self._to_cohere_chatmessage(messages)++ try:+ response = await self._async_client.chat(+ messages=cohere_messages,+ model=self.model_type,+ **request_config,)except ApiError as e:logging.error(f"Cohere API Error: {e.status_code}")diff --git a/camel/models/deepseek_model.py b/camel/models/deepseek_model.pyindex 56b694742..b8c9e100a 100644--- a/camel/models/deepseek_model.py+++ b/camel/models/deepseek_model.py@@ -13,13 +13,15 @@# ========= 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, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import DEEPSEEK_API_PARAMS, DeepSeekConfigfrom camel.logger import get_loggerfrom camel.messages import OpenAIMessage+from camel.models._utils import try_modify_message_with_formatfrom camel.models.base_model import BaseModelBackendfrom camel.types import (ChatCompletion,@@ -30,6 +32,16 @@ from camel.utils import BaseTokenCounter, OpenAITokenCounter, api_keys_requiredlogger = get_logger(__name__)+REASONSER_UNSUPPORTED_PARAMS = [+ "temperature",+ "top_p",+ "presence_penalty",+ "frequency_penalty",+ "logprobs",+ "top_logprobs",+ "tools",+]+class DeepSeekModel(BaseModelBackend):r"""DeepSeek API in a unified BaseModelBackend interface.@@ -84,6 +96,13 @@ class DeepSeekModel(BaseModelBackend):base_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )+@propertydef token_counter(self) -> BaseTokenCounter:r"""Initialize the token counter for the model backend.@@ -98,64 +117,51 @@ class DeepSeekModel(BaseModelBackend):)return self._token_counter- def run(+ def _prepare_request(self,messages: List[OpenAIMessage],- ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:- r"""Runs inference of DeepSeek chat completion.-- Args:- messages (List[OpenAIMessage]): Message list with the chat history- in OpenAI API format.+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Dict[str, Any]:+ request_config = self.model_config_dict.copy()- Returns:- Union[ChatCompletion, Stream[ChatCompletionChunk]]:- `ChatCompletion` in the non-stream mode, or- `Stream[ChatCompletionChunk]` in the stream mode.- """- # deepseek reasoner has limitations- # reference: https://api-docs.deepseek.com/guides/reasoning_model#api-parametersif self.model_type in [ModelType.DEEPSEEK_REASONER,]:logger.warning(- "You are using a DeepSeek Reasoner model, "+ "Warning: You are using an DeepSeek Reasoner model, ""which has certain limitations, reference: "- "`https://api-docs.deepseek.com/guides/reasoning_model#api-parameters`"+ "`https://api-docs.deepseek.com/guides/reasoning_model"+ "#api-parameters`.",)+ request_config = {+ key: value+ for key, value in request_config.items()+ if key not in REASONSER_UNSUPPORTED_PARAMS+ }- # Check and remove unsupported parameters and reset the fixed- # parameters- unsupported_keys = [- "temperature",- "top_p",- "presence_penalty",- "frequency_penalty",- "logprobs",- "top_logprobs",- "tools",- ]- for key in unsupported_keys:- if key in self.model_config_dict:- del self.model_config_dict[key]+ if tools:+ for tool in tools:+ function_dict = tool.get('function', {})+ function_dict.pop("strict", None)+ request_config["tools"] = tools+ elif response_format:+ try_modify_message_with_format(messages[-1], response_format)+ request_config["response_format"] = {"type": "json_object"}- response = self._client.chat.completions.create(- messages=messages,- model=self.model_type,- **self.model_config_dict,- )+ return request_config- # Handle reasoning content with <think> tags at the beginning+ def _post_handle_response(+ self, response: ChatCompletion+ ) -> ChatCompletion:+ r"""Handle reasoning content with <think> tags at the beginning."""if (- self.model_type- in [- ModelType.DEEPSEEK_REASONER,- ]+ self.model_type in [ModelType.DEEPSEEK_REASONER]and os.environ.get("GET_REASONING_CONTENT", "false").lower()== "true"):- reasoning_content = response.choices[0].message.reasoning_content- combined_content = (+ reasoning_content = response.choices[0].message.reasoning_content # type: ignore[attr-defined]+ combined_content = ( # type: ignore[operator]f"<think>\n{reasoning_content}\n</think>\n"if reasoning_contentelse ""@@ -181,9 +187,65 @@ class DeepSeekModel(BaseModelBackend):object="chat.completion",usage=response.usage,)-return response+ 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 DeepSeek chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ 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,+ **request_config,+ )++ return self._post_handle_response(response)++ 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 DeepSeek chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ 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,+ **request_config,+ )++ return self._post_handle_response(response)+def check_model_config(self):r"""Check whether the model configuration contains anyunexpected arguments to DeepSeek API.diff --git a/camel/models/gemini_model.py b/camel/models/gemini_model.pyindex 2da873998..ab7428383 100644--- a/camel/models/gemini_model.py+++ b/camel/models/gemini_model.py@@ -12,9 +12,10 @@# 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, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import Gemini_API_PARAMS, GeminiConfigfrom camel.messages import OpenAIMessage@@ -81,37 +82,154 @@ class GeminiModel(BaseModelBackend):api_key=self._api_key,base_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )- def run(+ def _process_messages(self, messages) -> List[OpenAIMessage]:+ r"""Process the messages for Gemini API to ensure no empty content,+ which is not accepted by Gemini.+ """+ processed_messages = []+ for msg in messages:+ msg_copy = msg.copy()+ if 'content' in msg_copy and msg_copy['content'] == '':+ msg_copy['content'] = 'null'+ processed_messages.append(msg_copy)+ return processed_messages++ 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 Gemini 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."""- # Process messages to ensure no empty content, it's not accepeted by- # Gemini- processed_messages = []- for msg in messages:- msg_copy = msg.copy()- if 'content' in msg_copy and msg_copy['content'] == '':- msg_copy['content'] = 'null'- processed_messages.append(msg_copy)+ response_format = response_format or self.model_config_dict.get(+ "response_format", None+ )+ messages = self._process_messages(messages)+ if response_format:+ return self._request_parse(messages, response_format)+ else:+ return self._request_chat_completion(messages, 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 in async mode.++ 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, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ response_format = response_format or self.model_config_dict.get(+ "response_format", None+ )+ messages = self._process_messages(messages)+ if response_format:+ return await self._arequest_parse(messages, response_format)+ else:+ return await self._arequest_chat_completion(messages, tools)++ def _request_chat_completion(+ self,+ messages: List[OpenAIMessage],+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ request_config = self.model_config_dict.copy()++ if tools:+ for tool in tools:+ function_dict = tool.get('function', {})+ function_dict.pop("strict", None)+ request_config["tools"] = tools++ return self._client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **request_config,+ )++ async def _arequest_chat_completion(+ self,+ messages: List[OpenAIMessage],+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ request_config = self.model_config_dict.copy()++ if tools:+ for tool in tools:+ function_dict = tool.get('function', {})+ function_dict.pop("strict", None)+ request_config["tools"] = tools++ return await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **request_config,+ )++ def _request_parse(+ self,+ messages: List[OpenAIMessage],+ response_format: Type[BaseModel],+ ) -> ChatCompletion:+ request_config = self.model_config_dict.copy()++ request_config["response_format"] = response_format+ request_config.pop("stream", None)++ 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],+ ) -> ChatCompletion:+ request_config = self.model_config_dict.copy()++ request_config["response_format"] = response_format+ request_config.pop("stream", None)- response = self._client.chat.completions.create(- messages=processed_messages,+ return await self._async_client.beta.chat.completions.parse(+ messages=messages,model=self.model_type,- **self.model_config_dict,+ **request_config,)- return response@propertydef token_counter(self) -> BaseTokenCounter:diff --git a/camel/models/groq_model.py b/camel/models/groq_model.pyindex 936533c88..963535f01 100644--- a/camel/models/groq_model.py+++ b/camel/models/groq_model.py@@ -14,7 +14,8 @@import osfrom typing import Any, Dict, List, Optional, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import GROQ_API_PARAMS, GroqConfigfrom camel.messages import OpenAIMessage@@ -79,6 +80,12 @@ class GroqModel(BaseModelBackend):api_key=self._api_key,base_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )@propertydef token_counter(self) -> BaseTokenCounter:@@ -92,9 +99,11 @@ class GroqModel(BaseModelBackend):self._token_counter = OpenAITokenCounter(ModelType.GPT_4O_MINI)return self._token_counter- def run(+ 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.@@ -115,6 +124,31 @@ class GroqModel(BaseModelBackend):return response+ 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.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )++ return response+def check_model_config(self):r"""Check whether the model configuration contains any unexpectedarguments to Groq API. But Groq API does not have any additionaldiff --git a/camel/models/internlm_model.py b/camel/models/internlm_model.pyindex a4a1be2d1..92b9c0c06 100644--- a/camel/models/internlm_model.py+++ b/camel/models/internlm_model.py@@ -13,9 +13,10 @@# ========= 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, Union-from openai import OpenAI, Stream+from openai import AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import INTERNLM_API_PARAMS, InternLMConfigfrom camel.messages import OpenAIMessage@@ -82,9 +83,11 @@ class InternLMModel(BaseModelBackend):base_url=self._url,)- def run(+ 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 InternLM chat completion.@@ -104,6 +107,14 @@ class InternLMModel(BaseModelBackend):)return response+ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ raise NotImplementedError("InternLM does not support async inference.")+@propertydef token_counter(self) -> BaseTokenCounter:r"""Initialize the token counter for the model backend.diff --git a/camel/models/litellm_model.py b/camel/models/litellm_model.pyindex e06feab66..f5acf950e 100644--- a/camel/models/litellm_model.py+++ b/camel/models/litellm_model.py@@ -11,7 +11,9 @@# See the License for the specific language governing permissions and# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Union++from pydantic import BaseModelfrom camel.configs import LITELLM_API_PARAMS, LiteLLMConfigfrom camel.messages import OpenAIMessage@@ -106,9 +108,14 @@ class LiteLLMModel(BaseModelBackend):self._token_counter = LiteLLMTokenCounter(self.model_type)return self._token_counter- def run(+ async def _arun(self) -> None: # type: ignore[override]+ raise NotImplementedError++ def _run(self,messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,) -> ChatCompletion:r"""Runs inference of LiteLLM chat completion.diff --git a/camel/models/mistral_model.py b/camel/models/mistral_model.pyindex e248e099e..a878263a6 100644--- a/camel/models/mistral_model.py+++ b/camel/models/mistral_model.py@@ -12,7 +12,9 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import os-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union++from pydantic import BaseModelif TYPE_CHECKING:from mistralai.models import (@@ -20,10 +22,13 @@ if TYPE_CHECKING:Messages,)+from openai import AsyncStream+from camel.configs import MISTRAL_API_PARAMS, MistralConfigfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackend-from camel.types import ChatCompletion, ModelType+from camel.models._utils import try_modify_message_with_format+from camel.types import ChatCompletion, ChatCompletionChunk, ModelTypefrom camel.utils import (BaseTokenCounter,OpenAITokenCounter,@@ -212,25 +217,42 @@ class MistralModel(BaseModelBackend):)return self._token_counter- def run(+ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ raise NotImplementedError("Mistral does not support async inference.")++ def _run(self,messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,) -> ChatCompletion:r"""Runs inference of Mistral 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 for this query.+ tools (Optional[List[Dict[str, Any]]]): The tools to use for this+ query.Returns:- ChatCompletion.+ ChatCompletion: The response from the model."""+ request_config = self._prepare_request(+ messages, response_format, tools+ )mistral_messages = self._to_mistral_chatmessage(messages)response = self._client.chat.complete(messages=mistral_messages,model=self.model_type,- **self.model_config_dict,+ **request_config,)openai_response = self._to_openai_response(response) # type: ignore[arg-type]@@ -251,6 +273,21 @@ class MistralModel(BaseModelBackend):return openai_response+ 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 check_model_config(self):r"""Check whether the model configuration contains anyunexpected arguments to Mistral API.diff --git a/camel/models/model_manager.py b/camel/models/model_manager.pyindex 3e324d0ed..f072af250 100644--- a/camel/models/model_manager.py+++ b/camel/models/model_manager.py@@ -20,10 +20,13 @@ from typing import (Callable,Dict,List,+ Optional,+ Type,Union,)-from openai import Stream+from openai import AsyncStream, Stream+from pydantic import BaseModelfrom camel.messages import OpenAIMessagefrom camel.models.base_model import BaseModelBackend@@ -178,7 +181,10 @@ class ModelManager:return choice(self.models)def run(- self, messages: List[OpenAIMessage]+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:r"""Process a list of messages by selecting a model based onthe scheduling strategy.@@ -198,7 +204,46 @@ class ModelManager:# Pass all messages to the selected model and get the responsetry:- response = self.current_model.run(messages)+ response = self.current_model.run(messages, response_format, tools)+ except Exception as exc:+ logger.error(f"Error processing with model: {self.current_model}")+ if self.scheduling_strategy == self.always_first:+ self.scheduling_strategy = self.round_robin+ logger.warning(+ "The scheduling strategy has been changed to 'round_robin'"+ )+ # Skip already used one+ self.current_model = self.scheduling_strategy()+ raise exc+ return response++ 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"""Process a list of messages by selecting a model based on+ the scheduling strategy.+ Sends the entire list of messages to the selected model,+ and returns a single response.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat+ history in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ self.current_model = self.scheduling_strategy()++ # Pass all messages to the selected model and get the response+ try:+ response = await self.current_model.arun(+ messages, response_format, tools+ )except Exception as exc:logger.error(f"Error processing with model: {self.current_model}")if self.scheduling_strategy == self.always_first:diff --git a/camel/models/moonshot_model.py b/camel/models/moonshot_model.pyindex d23f365be..b53d2994a 100644--- a/camel/models/moonshot_model.py+++ b/camel/models/moonshot_model.py@@ -13,9 +13,10 @@# ========= 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, Union-from openai import OpenAI, Stream+from openai import AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import MOONSHOT_API_PARAMS, MoonshotConfigfrom camel.messages import OpenAIMessage@@ -78,12 +79,15 @@ class MoonshotModel(BaseModelBackend):base_url=self._url,)- def run(+ 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 Moonshot chat completion.+Args:messages (List[OpenAIMessage]): Message list with the chat historyin OpenAI API format.@@ -100,6 +104,14 @@ class MoonshotModel(BaseModelBackend):)return response+ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ raise NotImplementedError("Moonshot does not support async inference.")+@propertydef token_counter(self) -> BaseTokenCounter:r"""Initialize the token counter for the model backend.diff --git a/camel/models/nemotron_model.py b/camel/models/nemotron_model.pyindex cc787ea93..8cdfe7168 100644--- a/camel/models/nemotron_model.py+++ b/camel/models/nemotron_model.py@@ -12,9 +12,10 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import os-from typing import List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Union-from openai import OpenAI+from openai import AsyncOpenAI, OpenAI+from pydantic import BaseModelfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackend@@ -62,10 +63,38 @@ class NemotronModel(BaseModelBackend):base_url=self._url,api_key=self._api_key,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ base_url=self._url,+ api_key=self._api_key,+ )++ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> ChatCompletion:+ r"""Runs inference of OpenAI chat completion asynchronously.++ Args:+ messages (List[OpenAIMessage]): Message list.++ Returns:+ ChatCompletion.+ """+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ )+ return response- def run(+ def _run(self,messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,) -> ChatCompletion:r"""Runs inference of OpenAI chat completion.diff --git a/camel/models/nvidia_model.py b/camel/models/nvidia_model.pyindex 732fb2ae2..e394e696c 100644--- a/camel/models/nvidia_model.py+++ b/camel/models/nvidia_model.py@@ -13,13 +13,14 @@# ========= 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, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Streamfrom openai.types.chat import (ChatCompletion,ChatCompletionChunk,)+from pydantic import BaseModelfrom camel.configs import NVIDIA_API_PARAMS, NvidiaConfigfrom camel.messages import OpenAIMessage@@ -76,10 +77,49 @@ class NvidiaModel(BaseModelBackend):api_key=self._api_key,base_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )++ 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 NVIDIA chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """++ # Remove tool-related parameters if no tools are specified+ config = dict(self.model_config_dict)+ if not config.get("tools"): # None or empty list+ config.pop("tools", None)+ config.pop("tool_choice", None)++ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **config,+ )+ return response- def run(+ 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 NVIDIA chat completion.diff --git a/camel/models/ollama_model.py b/camel/models/ollama_model.pyindex c0e2be59d..1d38023ae 100644--- a/camel/models/ollama_model.py+++ b/camel/models/ollama_model.py@@ -13,9 +13,10 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import osimport subprocess-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import OLLAMA_API_PARAMS, OllamaConfigfrom camel.messages import OpenAIMessage@@ -75,6 +76,12 @@ class OllamaModel(BaseModelBackend):api_key="Set-but-ignored", # required but ignoredbase_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key="Set-but-ignored", # required but ignored+ base_url=self._url,+ )def _start_server(self) -> None:r"""Starts the Ollama server in a subprocess."""@@ -119,9 +126,48 @@ class OllamaModel(BaseModelBackend):"input into Ollama model backend.")- def run(+ 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.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ 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,+ )++ return self._to_chat_completion(response)++ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )+ return response++ 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.diff --git a/camel/models/openai_audio_models.py b/camel/models/openai_audio_models.pyindex e4d05c8f9..5ecc3e33c 100644--- a/camel/models/openai_audio_models.py+++ b/camel/models/openai_audio_models.py@@ -14,7 +14,7 @@import osfrom typing import Any, List, Optional, Union-from openai import OpenAI, _legacy_response+from openai import AsyncOpenAI, OpenAI, _legacy_responsefrom camel.types import AudioModelType, VoiceType@@ -37,6 +37,12 @@ class OpenAIAudioModels:base_url=self._url,api_key=self._api_key,)+ self._async_client = AsyncOpenAI(+ timeout=120,+ max_retries=3,+ base_url=self._url,+ api_key=self._api_key,+ )def text_to_speech(self,diff --git a/camel/models/openai_compatible_model.py b/camel/models/openai_compatible_model.pyindex 204c475eb..d77cded87 100644--- a/camel/models/openai_compatible_model.py+++ b/camel/models/openai_compatible_model.py@@ -13,9 +13,10 @@# ========= 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, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackend@@ -67,9 +68,18 @@ class OpenAICompatibleModel(BaseModelBackend):base_url=self._url,)- def run(+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )++ 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.@@ -89,6 +99,30 @@ class OpenAICompatibleModel(BaseModelBackend):)return response+ 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 in async mode.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )+ return response+@propertydef token_counter(self) -> BaseTokenCounter:r"""Initialize the token counter for the model backend.diff --git a/camel/models/openai_model.py b/camel/models/openai_model.pyindex 0d905ef8a..2e7950f61 100644--- a/camel/models/openai_model.py+++ b/camel/models/openai_model.py@@ -13,9 +13,10 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import osimport warnings-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import OPENAI_API_PARAMS, ChatGPTConfigfrom camel.messages import OpenAIMessage@@ -31,6 +32,16 @@ from camel.utils import (api_keys_required,)+UNSUPPORTED_PARAMS = {+ "temperature",+ "top_p",+ "presence_penalty",+ "frequency_penalty",+ "logprobs",+ "top_logprobs",+ "logit_bias",+}+class OpenAIModel(BaseModelBackend):r"""OpenAI API in a unified BaseModelBackend interface.@@ -68,15 +79,45 @@ class OpenAIModel(BaseModelBackend):model_config_dict = ChatGPTConfig().as_dict()api_key = api_key or os.environ.get("OPENAI_API_KEY")url = url or os.environ.get("OPENAI_API_BASE_URL")+super().__init__(model_type, model_config_dict, api_key, url, token_counter)+self._client = OpenAI(timeout=180,max_retries=3,base_url=self._url,api_key=self._api_key,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ base_url=self._url,+ api_key=self._api_key,+ )++ def _sanitize_config(self, config_dict: Dict[str, Any]) -> Dict[str, Any]:+ """Sanitize the model configuration for O1 models."""++ if self.model_type in [+ ModelType.O1,+ ModelType.O1_MINI,+ ModelType.O1_PREVIEW,+ ModelType.O3_MINI,+ ]:+ warnings.warn(+ "Warning: You are using an O1 model (O1_MINI or O1_PREVIEW), "+ "which has certain limitations, reference: "+ "`https://platform.openai.com/docs/guides/reasoning`.",+ UserWarning,+ )+ return {+ k: v+ for k, v in config_dict.items()+ if k not in UNSUPPORTED_PARAMS+ }+ return config_dict@propertydef token_counter(self) -> BaseTokenCounter:@@ -90,70 +131,147 @@ class OpenAIModel(BaseModelBackend):self._token_counter = OpenAITokenCounter(self.model_type)return self._token_counter- def run(+ 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.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."""- # o1-preview and o1-mini have Beta limitations- # reference: https://platform.openai.com/docs/guides/reasoning- if self.model_type in [- ModelType.O1,- ModelType.O1_MINI,- ModelType.O1_PREVIEW,- ModelType.O3_MINI,- ]:- warnings.warn(- "Warning: You are using an O1 model (O1_MINI or O1_PREVIEW), "- "which has certain limitations, reference: "- "`https://platform.openai.com/docs/guides/reasoning`.",- UserWarning,- )+ response_format = response_format or self.model_config_dict.get(+ "response_format", None+ )+ if response_format:+ return self._request_parse(messages, response_format, tools)+ else:+ return self._request_chat_completion(messages, tools)- # Check and remove unsupported parameters and reset the fixed- # parameters- unsupported_keys = [- "temperature",- "top_p",- "presence_penalty",- "frequency_penalty",- "logprobs",- "top_logprobs",- "logit_bias",- ]- for key in unsupported_keys:- if key in self.model_config_dict:- del self.model_config_dict[key]-- 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,- )+ 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 in async mode.++ 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, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ 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, tools)++ def _request_chat_completion(+ self,+ messages: List[OpenAIMessage],+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ request_config = self.model_config_dict.copy()++ if tools:+ for tool in tools:+ function_dict = tool.get('function', {})+ function_dict.pop("strict", None)+ request_config["tools"] = tools++ request_config = self._sanitize_config(request_config)++ return self._client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **request_config,+ )++ async def _arequest_chat_completion(+ self,+ messages: List[OpenAIMessage],+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ request_config = self.model_config_dict.copy()++ if tools:+ for tool in tools:+ function_dict = tool.get('function', {})+ function_dict.pop("strict", None)+ request_config["tools"] = tools++ request_config = self._sanitize_config(request_config)++ return await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **request_config,+ )++ 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++ request_config = self._sanitize_config(request_config)++ 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()++ request_config["response_format"] = response_format+ request_config.pop("stream", None)+ if tools is not None:+ request_config["tools"] = tools- return self._to_chat_completion(response)+ request_config = self._sanitize_config(request_config)- 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 responsedef check_model_config(self):r"""Check whether the model configuration contains anydiff --git a/camel/models/qwen_model.py b/camel/models/qwen_model.pyindex 6c4c484f0..68f72836d 100644--- a/camel/models/qwen_model.py+++ b/camel/models/qwen_model.py@@ -13,13 +13,15 @@# ========= 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, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import QWEN_API_PARAMS, QwenConfigfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackend+from camel.models._utils import try_modify_message_with_formatfrom camel.types import (ChatCompletion,ChatCompletionChunk,@@ -81,10 +83,42 @@ class QwenModel(BaseModelBackend):api_key=self._api_key,base_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )++ 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 Qwen chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )+ return response- def run(+ 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 Qwen chat completion.@@ -97,13 +131,32 @@ class QwenModel(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 response+ 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+@propertydef token_counter(self) -> BaseTokenCounter:r"""Initialize the token counter for the model backend.diff --git a/camel/models/reka_model.py b/camel/models/reka_model.pyindex d2026da05..4dae7dd34 100644--- a/camel/models/reka_model.py+++ b/camel/models/reka_model.py@@ -11,7 +11,9 @@# See the License for the specific language governing permissions and# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union++from pydantic import BaseModelfrom camel.configs import REKA_API_PARAMS, RekaConfigfrom camel.messages import OpenAIMessage@@ -70,7 +72,7 @@ class RekaModel(BaseModelBackend):url: Optional[str] = None,token_counter: Optional[BaseTokenCounter] = None,) -> None:- from reka.client import Reka+ from reka.client import AsyncReka, Rekaif model_config_dict is None:model_config_dict = RekaConfig().as_dict()@@ -80,6 +82,9 @@ class RekaModel(BaseModelBackend):model_type, model_config_dict, api_key, url, token_counter)self._client = Reka(api_key=self._api_key, base_url=self._url)+ self._async_client = AsyncReka(+ api_key=self._api_key, base_url=self._url+ )def _convert_reka_to_openai_response(self, response: 'ChatResponse'@@ -117,6 +122,8 @@ class RekaModel(BaseModelBackend):def _convert_openai_to_reka_messages(self,messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[str]] = None,) -> List["ChatMessage"]:r"""Converts OpenAI API messages to Reka API messages.@@ -173,9 +180,52 @@ class RekaModel(BaseModelBackend):)return self._token_counter- def run(+ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> ChatCompletion:+ r"""Runs inference of Mistral chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ ChatCompletion.+ """+ reka_messages = self._convert_openai_to_reka_messages(messages)++ response = await self._async_client.chat.create(+ messages=reka_messages,+ model=self.model_type,+ **self.model_config_dict,+ )++ openai_response = self._convert_reka_to_openai_response(response)++ # Add AgentOps LLM Event tracking+ if LLMEvent:+ llm_event = LLMEvent(+ thread_id=openai_response.id,+ prompt=" ".join(+ [message.get("content") for message in messages] # type: ignore[misc]+ ),+ prompt_tokens=openai_response.usage.input_tokens, # type: ignore[union-attr]+ completion=openai_response.choices[0].message.content,+ completion_tokens=openai_response.usage.output_tokens, # type: ignore[union-attr]+ model=self.model_type,+ )+ record(llm_event)++ return openai_response++ def _run(self,messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,) -> ChatCompletion:r"""Runs inference of Mistral chat completion.diff --git a/camel/models/samba_model.py b/camel/models/samba_model.pyindex 4a5347b97..969df2d48 100644--- a/camel/models/samba_model.py+++ b/camel/models/samba_model.py@@ -15,10 +15,11 @@ import jsonimport osimport timeimport uuid-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Unionimport httpx-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import (SAMBA_CLOUD_API_PARAMS,@@ -105,6 +106,12 @@ class SambaModel(BaseModelBackend):base_url=self._url,api_key=self._api_key,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ base_url=self._url,+ api_key=self._api_key,+ )@propertydef token_counter(self) -> BaseTokenCounter:@@ -148,8 +155,35 @@ class SambaModel(BaseModelBackend):" SambaNova service")- def run( # type: ignore[misc]- self, messages: List[OpenAIMessage]+ async def _arun( # type: ignore[misc]+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ r"""Runs SambaNova's service.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ if "tools" in self.model_config_dict:+ del self.model_config_dict["tools"]+ if self.model_config_dict.get("stream") is True:+ return await self._arun_streaming(messages)+ else:+ return await self._arun_non_streaming(messages)++ def _run( # type: ignore[misc]+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:r"""Runs SambaNova's service.@@ -398,3 +432,174 @@ class SambaModel(BaseModelBackend):bool: Whether the model is in stream mode."""return self.model_config_dict.get('stream', False)++ async def _arun_streaming(+ self, messages: List[OpenAIMessage]+ ) -> AsyncStream[ChatCompletionChunk]:+ r"""Handles streaming inference with SambaNova's API.++ Args:+ messages (List[OpenAIMessage]): A list of messages representing the+ chat history in OpenAI API format.++ Returns:+ AsyncStream[ChatCompletionChunk]: A generator yielding+ `ChatCompletionChunk` objects as they are received from the+ API.++ Raises:+ RuntimeError: If the HTTP request fails.+ ValueError: If the API doesn't support stream mode.+ """+ # Handle SambaNova's Cloud API+ if self._url == "https://api.sambanova.ai/v1":+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )++ # Add AgentOps LLM Event tracking+ if LLMEvent:+ llm_event = LLMEvent(+ thread_id=response.id,+ prompt=" ".join(+ [message.get("content") for message in messages] # type: ignore[misc]+ ),+ prompt_tokens=response.usage.prompt_tokens, # type: ignore[union-attr]+ completion=response.choices[0].message.content,+ completion_tokens=response.usage.completion_tokens, # type: ignore[union-attr]+ model=self.model_type,+ )+ record(llm_event)++ return response++ elif self._url == "https://sambaverse.sambanova.ai/api/predict":+ raise ValueError(+ "https://sambaverse.sambanova.ai/api/predict doesn't support"+ " stream mode"+ )+ raise RuntimeError(f"Unknown URL: {self._url}")++ async def _arun_non_streaming(+ self, messages: List[OpenAIMessage]+ ) -> ChatCompletion:+ r"""Handles non-streaming inference with SambaNova's API.++ Args:+ messages (List[OpenAIMessage]): A list of messages representing the+ message in OpenAI API format.++ Returns:+ ChatCompletion: A `ChatCompletion` object containing the complete+ response from the API.++ Raises:+ RuntimeError: If the HTTP request fails.+ ValueError: If the JSON response cannot be decoded or is missing+ expected data.+ """+ # Handle SambaNova's Cloud API+ if self._url == "https://api.sambanova.ai/v1":+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )++ # Add AgentOps LLM Event tracking+ if LLMEvent:+ llm_event = LLMEvent(+ thread_id=response.id,+ prompt=" ".join(+ [message.get("content") for message in messages] # type: ignore[misc]+ ),+ prompt_tokens=response.usage.prompt_tokens, # type: ignore[union-attr]+ completion=response.choices[0].message.content,+ completion_tokens=response.usage.completion_tokens, # type: ignore[union-attr]+ model=self.model_type,+ )+ record(llm_event)++ return response++ # Handle SambaNova's Sambaverse API+ else:+ headers = {+ "Content-Type": "application/json",+ "key": str(self._api_key),+ "modelName": self.model_type,+ }++ data = {+ "instance": json.dumps(+ {+ "conversation_id": str(uuid.uuid4()),+ "messages": messages,+ }+ ),+ "params": {+ "do_sample": {"type": "bool", "value": "true"},+ "max_tokens_to_generate": {+ "type": "int",+ "value": str(self.model_config_dict.get("max_tokens")),+ },+ "process_prompt": {"type": "bool", "value": "true"},+ "repetition_penalty": {+ "type": "float",+ "value": str(+ self.model_config_dict.get("repetition_penalty")+ ),+ },+ "return_token_count_only": {+ "type": "bool",+ "value": "false",+ },+ "select_expert": {+ "type": "str",+ "value": self.model_type.split("/")[1],+ },+ "stop_sequences": {+ "type": "str",+ "value": self.model_config_dict.get("stop_sequences"),+ },+ "temperature": {+ "type": "float",+ "value": str(+ self.model_config_dict.get("temperature")+ ),+ },+ "top_k": {+ "type": "int",+ "value": str(self.model_config_dict.get("top_k")),+ },+ "top_p": {+ "type": "float",+ "value": str(self.model_config_dict.get("top_p")),+ },+ },+ }++ try:+ # Send the request and handle the response+ with httpx.Client() as client:+ response = client.post(+ self._url, # type: ignore[arg-type]+ headers=headers,+ json=data,+ )++ raw_text = response.text+ # Split the string into two dictionaries+ dicts = raw_text.split("}\n{")++ # Keep only the last dictionary+ last_dict = "{" + dicts[-1]++ # Parse the dictionary+ last_dict = json.loads(last_dict)+ return self._sambaverse_to_openai_response(last_dict) # type: ignore[arg-type]++ except httpx.HTTPStatusError:+ raise RuntimeError(f"HTTP request failed: {raw_text}")diff --git a/camel/models/sglang_model.py b/camel/models/sglang_model.pyindex 5369f3db5..14a4dd57b 100644--- a/camel/models/sglang_model.py+++ b/camel/models/sglang_model.py@@ -14,9 +14,10 @@import loggingimport threadingimport time-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import SGLANG_API_PARAMS, SGLangConfigfrom camel.messages import OpenAIMessage@@ -85,6 +86,12 @@ class SGLangModel(BaseModelBackend):api_key="Set-but-ignored", # required but ignoredbase_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key="Set-but-ignored", # required but ignored+ base_url=self._url,+ )def _start_server(self) -> None:from sglang.utils import ( # type: ignore[import-untyped]@@ -178,9 +185,49 @@ class SGLangModel(BaseModelBackend):"input into SGLang model backend.")- def run(+ 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.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """++ # Ensure server is running+ self._ensure_server_running()++ with self._lock:+ # Update last run time+ self.last_run_time = time.time()++ if self._client is None:+ raise RuntimeError(+ "Client is not initialized. Ensure the server is running."+ )++ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )++ return response++ 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.diff --git a/camel/models/siliconflow_model.py b/camel/models/siliconflow_model.pyindex c981472bc..f1a950800 100644--- a/camel/models/siliconflow_model.py+++ b/camel/models/siliconflow_model.py@@ -12,9 +12,10 @@# 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, Union-from openai import OpenAI, Stream+from openai import AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import SILICONFLOW_API_PARAMS, SiliconFlowConfigfrom camel.messages import OpenAIMessage@@ -82,9 +83,11 @@ class SiliconFlowModel(BaseModelBackend):base_url=self._url,)- def run(+ 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 SiliconFlow chat completion.@@ -104,6 +107,16 @@ class SiliconFlowModel(BaseModelBackend):)return response+ async def _arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ raise NotImplementedError(+ "SiliconFlow does not support async inference."+ )+@propertydef token_counter(self) -> BaseTokenCounter:r"""Initialize the token counter for the model backend.diff --git a/camel/models/stub_model.py b/camel/models/stub_model.pyindex e85e1298f..066dc9e57 100644--- a/camel/models/stub_model.py+++ b/camel/models/stub_model.py@@ -12,9 +12,10 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import time-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Union-from openai import Stream+from openai import AsyncStream, Stream+from pydantic import BaseModelfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackend@@ -74,8 +75,49 @@ class StubModel(BaseModelBackend):self._token_counter = StubTokenCounter()return self._token_counter- def run(- self, messages: List[OpenAIMessage]+ 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"""Run fake inference by returning a fixed string.+ All arguments are unused for the dummy model.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ The response from the dummy model.+ """+ ARBITRARY_STRING = "Lorem Ipsum"+ response: ChatCompletion = ChatCompletion(+ id="stub_model_id",+ model="stub",+ object="chat.completion",+ created=int(time.time()),+ choices=[+ Choice(+ finish_reason="stop",+ index=0,+ message=ChatCompletionMessage(+ content=ARBITRARY_STRING,+ role="assistant",+ ),+ logprobs=None,+ )+ ],+ usage=CompletionUsage(+ completion_tokens=10,+ prompt_tokens=10,+ total_tokens=20,+ ),+ )+ return response++ def _run(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:r"""Run fake inference by returning a fixed string.All arguments are unused for the dummy model.diff --git a/camel/models/togetherai_model.py b/camel/models/togetherai_model.pyindex 824942f30..8601e697c 100644--- a/camel/models/togetherai_model.py+++ b/camel/models/togetherai_model.py@@ -13,9 +13,10 @@# ========= 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, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import TOGETHERAI_API_PARAMS, TogetherAIConfigfrom camel.messages import OpenAIMessage@@ -82,10 +83,44 @@ class TogetherAIModel(BaseModelBackend):api_key=self._api_key,base_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )++ 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.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ # Use OpenAI cilent as interface call Together AI+ # Reference: https://docs.together.ai/docs/openai-api-compatibility+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )+ return response- def run(+ 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.diff --git a/camel/models/vllm_model.py b/camel/models/vllm_model.pyindex 7493f5309..353655e6f 100644--- a/camel/models/vllm_model.py+++ b/camel/models/vllm_model.py@@ -13,9 +13,10 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import osimport subprocess-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Type, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import VLLM_API_PARAMS, VLLMConfigfrom camel.messages import OpenAIMessage@@ -77,6 +78,12 @@ class VLLMModel(BaseModelBackend):api_key="EMPTY", # required but ignoredbase_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key="EMPTY", # required but ignored+ base_url=self._url,+ )def _start_server(self) -> None:r"""Starts the vllm server in a subprocess."""@@ -121,9 +128,36 @@ class VLLMModel(BaseModelBackend):"input into vLLM model backend.")- def run(+ 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.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """++ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )+ return response++ 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.diff --git a/camel/models/yi_model.py b/camel/models/yi_model.pyindex 96758d7d7..447810456 100644--- a/camel/models/yi_model.py+++ b/camel/models/yi_model.py@@ -13,9 +13,10 @@# ========= 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, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import YI_API_PARAMS, YiConfigfrom camel.messages import OpenAIMessage@@ -80,10 +81,42 @@ class YiModel(BaseModelBackend):api_key=self._api_key,base_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )++ 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 Yi chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )+ return response- def run(+ 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 Yi chat completion.diff --git a/camel/models/zhipuai_model.py b/camel/models/zhipuai_model.pyindex 0be8a6f39..f737cb2f8 100644--- a/camel/models/zhipuai_model.py+++ b/camel/models/zhipuai_model.py@@ -13,9 +13,10 @@# ========= 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, Union-from openai import OpenAI, Stream+from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModelfrom camel.configs import ZHIPUAI_API_PARAMS, ZhipuAIConfigfrom camel.messages import OpenAIMessage@@ -80,10 +81,44 @@ class ZhipuAIModel(BaseModelBackend):api_key=self._api_key,base_url=self._url,)+ self._async_client = AsyncOpenAI(+ timeout=180,+ max_retries=3,+ api_key=self._api_key,+ base_url=self._url,+ )++ 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.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `AsyncStream[ChatCompletionChunk]` in the stream mode.+ """+ # Use OpenAI cilent as interface call ZhipuAI+ # Reference: https://open.bigmodel.cn/dev/api#openai_sdk+ response = await self._async_client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **self.model_config_dict,+ )+ return response- def run(+ 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.diff --git a/camel/toolkits/function_tool.py b/camel/toolkits/function_tool.pyindex 6a081e792..737d130ea 100644--- a/camel/toolkits/function_tool.py+++ b/camel/toolkits/function_tool.py@@ -398,6 +398,19 @@ class FunctionTool:f"Error: {e}")+ async def async_call(self, *args: Any, **kwargs: Any) -> Any:+ if self.synthesize_output:+ result = self.synthesize_execution_output(args, kwargs)+ return result+ if self.is_async:+ return await self.func(*args, **kwargs)+ else:+ return self.func(*args, **kwargs)++ @property+ def is_async(self) -> bool:+ return inspect.iscoroutinefunction(self.func)+@staticmethoddef validate_openai_tool_schema(openai_tool_schema: Dict[str, Any],diff --git a/camel/types/__init__.py b/camel/types/__init__.pyindex 1948c2cb4..8a0729e2a 100644--- a/camel/types/__init__.py+++ b/camel/types/__init__.py@@ -73,8 +73,8 @@ __all__ = ['AudioModelType','VoiceType','UnifiedModelType',- 'NOT_GIVEN',- 'NotGiven','ParsedChatCompletion','HuggingFaceRepoType',+ 'NOT_GIVEN',+ 'NotGiven',]diff --git a/camel/types/agents/__init__.py b/camel/types/agents/__init__.pynew file mode 100644index 000000000..da547307e--- /dev/null+++ b/camel/types/agents/__init__.py@@ -0,0 +1,16 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+from .tool_calling_record import ToolCallingRecord++__all__ = ["ToolCallingRecord"]diff --git a/camel/types/agents/tool_calling_record.py b/camel/types/agents/tool_calling_record.pynew file mode 100644index 000000000..d3359b4de--- /dev/null+++ b/camel/types/agents/tool_calling_record.py@@ -0,0 +1,52 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+from typing import Any, Dict++from pydantic import BaseModel+++class ToolCallingRecord(BaseModel):+ r"""Historical records of tools called in the conversation.++ Attributes:+ func_name (str): The name of the tool being called.+ args (Dict[str, Any]): The dictionary of arguments passed to the tool.+ result (Any): The execution result of calling this tool.+ tool_call_id (str): The ID of the tool call, if available.+ """++ tool_name: str+ args: Dict[str, Any]+ result: Any+ tool_call_id: str++ def __str__(self) -> str:+ r"""Overridden version of the string function.++ Returns:+ str: Modified string to represent the tool calling.+ """+ return (+ f"Tool Execution: {self.tool_name}\n"+ f"\tArgs: {self.args}\n"+ f"\tResult: {self.result}\n"+ )++ def as_dict(self) -> dict[str, Any]:+ r"""Returns the tool calling record as a dictionary.++ Returns:+ dict[str, Any]: The tool calling record as a dictionary.+ """+ return self.model_dump()diff --git a/camel/types/openai_types.py b/camel/types/openai_types.pyindex 66449bdfb..14ad3e567 100644--- a/camel/types/openai_types.py+++ b/camel/types/openai_types.py@@ -35,17 +35,19 @@ from openai.types.chat import ParsedChatCompletionfrom openai._types import NOT_GIVEN, NotGivenfrom openai.types.chat import ChatCompletionMessageToolCall-Choice = Choice-ChatCompletion = ChatCompletion-ChatCompletionChunk = ChatCompletionChunk-ChatCompletionMessage = ChatCompletionMessage-ChatCompletionMessageParam = ChatCompletionMessageParam-ChatCompletionSystemMessageParam = ChatCompletionSystemMessageParam-ChatCompletionUserMessageParam = ChatCompletionUserMessageParam-ChatCompletionAssistantMessageParam = ChatCompletionAssistantMessageParam-ChatCompletionToolMessageParam = ChatCompletionToolMessageParam-ChatCompletionMessageToolCall = ChatCompletionMessageToolCall-CompletionUsage = CompletionUsage-NOT_GIVEN = NOT_GIVEN-NotGiven = NotGiven-ParsedChatCompletion = ParsedChatCompletion+__all__ = [+ "Choice",+ "ChatCompletion",+ "ChatCompletionChunk",+ "ChatCompletionMessage",+ "ChatCompletionMessageParam",+ "ChatCompletionSystemMessageParam",+ "ChatCompletionUserMessageParam",+ "ChatCompletionAssistantMessageParam",+ "ChatCompletionToolMessageParam",+ "ChatCompletionMessageToolCall",+ "CompletionUsage",+ "ParsedChatCompletion",+ "NOT_GIVEN",+ "NotGiven",+]diff --git a/camel/utils/__init__.py b/camel/utils/__init__.pyindex c08c62c14..7ac7f0a8d 100644--- a/camel/utils/__init__.py+++ b/camel/utils/__init__.py@@ -23,7 +23,6 @@ from .commons import (download_github_subdirectory,download_tasks,func_string_to_callable,- generate_prompt_for_structured_output,get_first_int,get_prompt_template_key_words,get_pydantic_major_version,diff --git a/camel/utils/async_func.py b/camel/utils/async_func.pyindex 2e1c612ab..69e4d01bf 100644--- a/camel/utils/async_func.py+++ b/camel/utils/async_func.py@@ -33,8 +33,8 @@ def sync_funcs_to_async(funcs: list[FunctionTool]) -> list[FunctionTool]:for func in funcs:sync_func = func.func- def async_callable(*args, **kwargs):- return asyncio.to_thread(sync_func, *args, **kwargs) # noqa: B023+ async def async_callable(*args, **kwargs):+ return await asyncio.to_thread(sync_func, *args, **kwargs) # noqa: B023async_funcs.append(FunctionTool(async_callable, deepcopy(func.openai_tool_schema))diff --git a/camel/utils/commons.py b/camel/utils/commons.pyindex 29a82f86a..b16ec0893 100644--- a/camel/utils/commons.py+++ b/camel/utils/commons.py@@ -869,39 +869,3 @@ def download_github_subdirectory(download_github_subdirectory(repo, f'{subdir}/{file["name"]}', file_path, branch)---def generate_prompt_for_structured_output(- response_format: Optional[Type[BaseModel]],- user_message: str,-) -> str:- """- This function generates a prompt based on the provided Pydantic model and- user message.-- Args:- response_format (Type[BaseModel]): The Pydantic model class.- user_message (str): The user message to be used in the prompt.-- Returns:- str: A prompt string for the LLM.- """- if response_format is None:- return user_message-- json_schema = response_format.model_json_schema()- sys_prompt = (- "Given the user message, please generate a JSON response adhering "- "to the following JSON schema:\n"- f"{json_schema}\n"- "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.\n"- )- user_prompt = f"User message: {user_message}\n"-- final_prompt = f"""- {sys_prompt}- {user_prompt}- """- return final_promptdiff --git a/examples/models/nemotron_model_example.py b/examples/models/nemotron_model_example.pyindex 0b465d056..d9067ad5d 100644--- a/examples/models/nemotron_model_example.py+++ b/examples/models/nemotron_model_example.py@@ -26,7 +26,7 @@ message = [},]-ans = nemotron.run(message)+ans = nemotron._run(message)print(ans)'''===============================================================================diff --git a/examples/toolkits/role_playing_with_functions.py b/examples/toolkits/role_playing_with_functions.pyindex 157ea4bf1..4950d9911 100644--- a/examples/toolkits/role_playing_with_functions.py+++ b/examples/toolkits/role_playing_with_functions.py@@ -17,7 +17,6 @@ from typing import Listfrom colorama import Forefrom camel.agents.chat_agent import ToolCallingRecord-from camel.configs import ChatGPTConfigfrom camel.models import ModelFactoryfrom camel.societies import RolePlayingfrom camel.toolkits import (@@ -29,8 +28,8 @@ from camel.utils import print_text_animateddef main(- model_platform=ModelPlatformType.DEFAULT,- model_type=ModelType.DEFAULT,+ model_platform=ModelPlatformType.NVIDIA,+ model_type=ModelType.NVIDIA_LLAMA3_3_70B_INSTRUCT,chat_turn_limit=10,) -> None:task_prompt = (@@ -38,18 +37,13 @@ def main("estimate the current age of University of Oxford ""and then add 10 more years to this age, ""and get the current weather of the city where "- "the University is located."+ "the University is located. You must use tool to solve the task.")- user_model_config = ChatGPTConfig(temperature=0.0)-tools_list = [*MathToolkit().get_tools(),- *SearchToolkit().get_tools(),+ SearchToolkit().search_duckduckgo,]- assistant_model_config = ChatGPTConfig(- temperature=0.0,- )role_play_session = RolePlaying(assistant_role_name="Searcher",@@ -58,7 +52,6 @@ def main(model=ModelFactory.create(model_platform=model_platform,model_type=model_type,- model_config_dict=assistant_model_config.as_dict(),),tools=tools_list,),@@ -66,7 +59,6 @@ def main(model=ModelFactory.create(model_platform=model_platform,model_type=model_type,- model_config_dict=user_model_config.as_dict(),),),task_prompt=task_prompt,diff --git a/poetry.lock b/poetry.lockindex ef22d8864..96d509b6d 100644--- a/poetry.lock+++ b/poetry.lock@@ -1,4 +1,4 @@-# This file is automatically @generated by Poetry 1.8.5 and should not be changed by hand.+# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.[[package]]name = "accelerate"diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.pyindex 29f63819b..870a2ba14 100644--- a/test/agents/test_chat_agent.py+++ b/test/agents/test_chat_agent.py@@ -361,9 +361,11 @@ def test_chat_agent_step_with_external_tools(step_call_count=3):response = external_tool_agent.step(usr_msg)assert not response.msg.content- external_tool_request = response.info["external_tool_request"]+ external_tool_call_request = response.info[+ "external_tool_call_request"+ ]assert (- external_tool_request.function.name == "sub"+ external_tool_call_request.tool_name == "sub"), f"Error in calling round {i+1}"@@ -449,20 +451,6 @@ def test_chat_agent_multiple_return_messages(n, step_call_count=3):content="What do you call fake spaghetti? An impasta!",role="assistant",function_call=None,- tool_calls=[- ChatCompletionMessageToolCall(- id="call_mock123456",- function=Function(- arguments='{ \- "joke":"What do you call fake spaghetti?" \- " An impasta!", \- "funny_level":"6" \- }',- name="return_json_response",- ),- type="function",- )- ],),)]@@ -630,7 +618,7 @@ def test_set_output_language():# Set the output language to "Arabic"output_language = "Arabic"- agent.set_output_language(output_language)+ agent.output_language = output_language# Check if the output language is set correctlyassert agent.output_language == output_language@@ -658,12 +646,12 @@ def test_set_multiple_output_language():# Verify that the length of the system message is kept constant even when# multiple set_output_language operations are called- agent_with_sys_msg.set_output_language("Chinese")- agent_with_sys_msg.set_output_language("English")- agent_with_sys_msg.set_output_language("French")- agent_without_sys_msg.set_output_language("Chinese")- agent_without_sys_msg.set_output_language("English")- agent_without_sys_msg.set_output_language("French")+ agent_with_sys_msg.output_language = "Chinese"+ agent_with_sys_msg.output_language = "English"+ agent_with_sys_msg.output_language = "French"+ agent_without_sys_msg.output_language = "Chinese"+ agent_without_sys_msg.output_language = "English"+ agent_without_sys_msg.output_language = "French"updated_system_message_with_sys_msg = {'role': 'system',@@ -689,29 +677,6 @@ def test_set_multiple_output_language():)[email protected]_backend-def test_function_enabled():- system_message = BaseMessage(- role_name="assistant",- role_type=RoleType.ASSISTANT,- meta_dict=None,- content="You are a help assistant.",- )- model = ModelFactory.create(- model_platform=ModelPlatformType.OPENAI,- model_type=ModelType.GPT_4O_MINI,- )- agent_no_func = ChatAgent(system_message=system_message)- agent_with_funcs = ChatAgent(- system_message=system_message,- model=model,- tools=MathToolkit().get_tools(),- )-- assert not agent_no_func.is_tools_added()- assert agent_with_funcs.is_tools_added()--@pytest.mark.model_backenddef test_tool_calling_sync(step_call_count=3):system_message = BaseMessage(@@ -980,7 +945,7 @@ async def test_tool_calling_math_async(step_call_count=3):)for i in range(step_call_count):- agent_response = await agent.step_async(user_msg)+ agent_response = await agent.astep(user_msg)tool_calls = agent_response.info['tool_calls']@@ -1068,7 +1033,7 @@ async def test_tool_calling_async(step_call_count=3):)for i in range(step_call_count):- agent_response = await agent.step_async(user_msg)+ agent_response = await agent.astep(user_msg)tool_calls = agent_response.info['tool_calls']diff --git a/test/models/test_base_model.py b/test/models/test_base_model.pyindex f84b7b1e1..06e6688d3 100644--- a/test/models/test_base_model.py+++ b/test/models/test_base_model.py@@ -34,6 +34,12 @@ class TestBaseModelBackend:def check_model_config(self):pass+ def _run(self, messages, response_format=None, tools=None):+ pass++ async def _arun(self, messages, response_format=None, tools=None):+ pass+model = DummyModel(ModelType.GPT_4O_MINI)# Test basic thinking removal@@ -78,6 +84,12 @@ class TestBaseModelBackend:def check_model_config(self):pass+ def _run(self, messages, response_format=None, tools=None):+ pass++ async def _arun(self, messages, response_format=None, tools=None):+ pass+model = TestModel(ModelType.GPT_4O_MINI)messages = [{'role': 'user', 'content': 'Hello <think>hi</think> world'}diff --git a/test/models/test_model_factory.py b/test/models/test_model_factory.pyindex 88042faa2..58f4a6fed 100644--- a/test/models/test_model_factory.py+++ b/test/models/test_model_factory.py@@ -30,7 +30,7 @@ from camel.utils import (parametrize = pytest.mark.parametrize('model_platform, model_type',[- (ModelPlatformType.OPENAI, ModelType.GPT_3_5_TURBO),+ (ModelPlatformType.OPENAI, ModelType.GPT_4O),(ModelPlatformType.OPENAI, ModelType.GPT_4O_MINI),],)