🐫 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: move from function to tools (#556)
Wendong-Fan52eb39f5ac0d
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 5e6feb5ba..2b7c28cd0 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -96,7 +96,7 @@ class ChatAgent(BaseAgent):(default: :obj:`None`)output_language (str, optional): The language to be output by theagent. (default: :obj:`None`)- function_list (List[OpenAIFunction], optional): List of available+ tools (List[OpenAIFunction], optional): List of available:obj:`OpenAIFunction`. (default: :obj:`None`)response_terminators (List[ResponseTerminator], optional): List of:obj:`ResponseTerminator` bind to one chat agent.@@ -112,7 +112,7 @@ class ChatAgent(BaseAgent):message_window_size: Optional[int] = None,token_limit: Optional[int] = None,output_language: Optional[str] = None,- function_list: Optional[List[OpenAIFunction]] = None,+ tools: Optional[List[OpenAIFunction]] = None,response_terminators: Optional[List[ResponseTerminator]] = None,) -> None:self.orig_sys_message: BaseMessage = system_message@@ -128,8 +128,8 @@ class ChatAgent(BaseAgent):)self.func_dict: Dict[str, Callable] = {}- if function_list is not None:- for func in function_list:+ if tools is not None:+ for func in tools:self.func_dict[func.get_function_name()] = func.funcself.model_config = model_config or ChatGPTConfig()@@ -181,12 +181,12 @@ class ChatAgent(BaseAgent):"""self._system_message = message- def is_function_calling_enabled(self) -> bool:+ def is_tools_added(self) -> bool:r"""Whether OpenAI function calling is enabled for this agent.Returns:bool: Whether OpenAI function calling is enabled for this- agent, determined by whether the dictionary of functions+ agent, determined by whether the dictionary of toolsis empty."""return len(self.func_dict) > 0@@ -229,7 +229,7 @@ class ChatAgent(BaseAgent):usage: Optional[Dict[str, int]],termination_reasons: List[str],num_tokens: int,- called_funcs: List[FunctionCallingRecord],+ tool_calls: List[FunctionCallingRecord],) -> Dict[str, Any]:r"""Returns a dictionary containing information about the chat session.@@ -240,9 +240,9 @@ class ChatAgent(BaseAgent):termination_reasons (List[str]): The reasons for the terminationof the chat session.num_tokens (int): The number of tokens used in the chat session.- called_funcs (List[FunctionCallingRecord]): The list of function+ tool_calls (List[FunctionCallingRecord]): The list of functioncalling records, containing the information of called- functions.+ tools.Returns:Dict[str, Any]: The chat session information.@@ -252,7 +252,7 @@ class ChatAgent(BaseAgent):"usage": usage,"termination_reasons": termination_reasons,"num_tokens": num_tokens,- "called_functions": called_funcs,+ "tool_calls": tool_calls,}def init_messages(self) -> None:@@ -285,9 +285,10 @@ class ChatAgent(BaseAgent):Args:input_message (BaseMessage): The input message to the agent.- Its `role` field that specifies the role at backend may be either- `user` or `assistant` but it will be set to `user` anyway since- for the self agent any incoming message is external.+ Its `role` field that specifies the role at backend may be+ either `user` or `assistant` but it will be set to `user`+ anyway since for the self agent any incoming message is+ external.Returns:ChatAgentResponse: A struct containing the output messages,@@ -298,7 +299,7 @@ class ChatAgent(BaseAgent):output_messages: List[BaseMessage]info: Dict[str, Any]- called_funcs: List[FunctionCallingRecord] = []+ tool_calls: List[FunctionCallingRecord] = []while True:# Format messages and get the token numberopenai_messages: Optional[List[OpenAIMessage]]@@ -307,7 +308,7 @@ class ChatAgent(BaseAgent):openai_messages, num_tokens = self.memory.get_context()except RuntimeError as e:return self.step_token_exceed(- e.args[1], called_funcs, "max_tokens_exceeded"+ e.args[1], tool_calls, "max_tokens_exceeded")# Obtain the model's response@@ -323,13 +324,15 @@ class ChatAgent(BaseAgent):)if (- self.is_function_calling_enabled()- and finish_reasons[0] == 'function_call'+ self.is_tools_added()and isinstance(response, ChatCompletion)+ and response.choices[0].message.tool_calls is not None):+ # Tools added for function calling and not in stream mode+# Do function callingfunc_assistant_msg, func_result_msg, func_record = (- self.step_function_call(response)+ self.step_tool_call(response))# Update the messages@@ -339,7 +342,8 @@ class ChatAgent(BaseAgent):self.update_memory(func_result_msg, OpenAIBackendRole.FUNCTION)# Record the function calling- called_funcs.append(func_record)+ tool_calls.append(func_record)+else:# Function calling disabled or not a function calling@@ -368,7 +372,7 @@ class ChatAgent(BaseAgent):usage_dict,finish_reasons,num_tokens,- called_funcs,+ tool_calls,)break@@ -455,7 +459,7 @@ class ChatAgent(BaseAgent):def step_token_exceed(self,num_tokens: int,- called_funcs: List[FunctionCallingRecord],+ tool_calls: List[FunctionCallingRecord],termination_reason: str,) -> ChatAgentResponse:r"""Return trivial response containing number of tokens and information@@ -463,7 +467,7 @@ class ChatAgent(BaseAgent):Args:num_tokens (int): Number of tokens in the messages.- called_funcs (List[FunctionCallingRecord]): List of information+ tool_calls (List[FunctionCallingRecord]): List of informationobjects of functions called in the current step.termination_reason (str): String of termination reason.@@ -479,7 +483,7 @@ class ChatAgent(BaseAgent):None,[termination_reason],num_tokens,- called_funcs,+ tool_calls,)return ChatAgentResponse(@@ -488,7 +492,7 @@ class ChatAgent(BaseAgent):info,)- def step_function_call(+ def step_tool_call(self,response: ChatCompletion,) -> Tuple[@@ -506,14 +510,13 @@ class ChatAgent(BaseAgent):result, and a struct for logging information about thisfunction call."""- # Note that when function calling is enabled, `n` is set to 1.choice = response.choices[0]- if choice.message.function_call is None:- raise RuntimeError("Function call is None")- func_name = choice.message.function_call.name+ if choice.message.tool_calls is None:+ raise RuntimeError("Tool calls is None")+ func_name = choice.message.tool_calls[0].function.namefunc = self.func_dict[func_name]- args_str: str = choice.message.function_call.arguments+ args_str: str = choice.message.tool_calls[0].function.argumentsargs = json.loads(args_str.replace("'", "\""))# Pass the extracted arguments to the indicated functiondiff --git a/camel/configs/__init__.py b/camel/configs/__init__.pyindex 211079018..3b8209c37 100644--- a/camel/configs/__init__.py+++ b/camel/configs/__init__.py@@ -15,18 +15,14 @@ from .anthropic_config import ANTHROPIC_API_PARAMS, AnthropicConfigfrom .base_config import BaseConfigfrom .openai_config import (OPENAI_API_PARAMS,- OPENAI_API_PARAMS_WITH_FUNCTIONS,ChatGPTConfig,- FunctionCallingConfig,OpenSourceConfig,)__all__ = ['BaseConfig','ChatGPTConfig',- 'FunctionCallingConfig','OPENAI_API_PARAMS',- 'OPENAI_API_PARAMS_WITH_FUNCTIONS','AnthropicConfig','ANTHROPIC_API_PARAMS','OpenSourceConfig',diff --git a/camel/configs/openai_config.py b/camel/configs/openai_config.pyindex 993f64e97..348a8512c 100644--- a/camel/configs/openai_config.py+++ b/camel/configs/openai_config.py@@ -14,7 +14,7 @@from __future__ import annotationsfrom dataclasses import asdict, dataclass, field-from typing import TYPE_CHECKING, Any, Sequence+from typing import TYPE_CHECKING, Optional, Sequencefrom openai._types import NOT_GIVEN, NotGiven@@ -72,6 +72,20 @@ class ChatGPTConfig(BaseConfig):user (str, optional): A unique identifier representing your end-user,which can help OpenAI to monitor and detect abuse.(default: :obj:`""`)+ tools (list[OpenAIFunction], optional): A list of tools the model may+ call. Currently, only functions are supported as a tool. Use this+ to provide a list of functions the model may generate JSON inputs+ for. A max of 128 functions are supported.+ tool_choice (Union[dict[str, str], str], optional): Controls which (if+ any) tool is called by the model. :obj:`"none"` means the model+ will not call any tool and instead generates a message.+ :obj:`"auto"` means the model can pick between generating a+ message or calling one or more tools. :obj:`"required"` means the+ model must call one or more tools. Specifying a particular tool+ via {"type": "function", "function": {"name": "my_function"}}+ forces the model to call that tool. :obj:`"none"` is the default+ when no tools are present. :obj:`"auto"` is the default if tools+ are present."""temperature: float = 0.2 # openai default: 1.0@@ -84,65 +98,19 @@ class ChatGPTConfig(BaseConfig):frequency_penalty: float = 0.0logit_bias: dict = field(default_factory=dict)user: str = ""+ tools: Optional[list[OpenAIFunction]] = None+ tool_choice: Optional[dict[str, str] | str] = None--@dataclass(frozen=True)-class FunctionCallingConfig(ChatGPTConfig):- r"""Defines the parameters for generating chat completions using the- OpenAI API with functions included.-- Args:- functions (List[Dict[str, Any]]): A list of functions the model may- generate JSON inputs for.- function_call (Union[Dict[str, str], str], optional): Controls how the- model responds to function calls. :obj:`"none"` means the model- does not call a function, and responds to the end-user.- :obj:`"auto"` means the model can pick between an end-user or- calling a function. Specifying a particular function via- :obj:`{"name": "my_function"}` forces the model to call that- function. (default: :obj:`"auto"`)- """-- functions: list[dict[str, Any]] = field(default_factory=list)- function_call: dict[str, str] | str = "auto"-- @classmethod- def from_openai_function_list(- cls,- function_list: list[OpenAIFunction],- function_call: dict[str, str] | str = "auto",- kwargs: dict[str, Any] | None = None,- ):- r"""Class method for creating an instance given the function-related- arguments.-- Args:- function_list (List[OpenAIFunction]): The list of function objects- to be loaded into this configuration and passed to the model.- function_call (Union[Dict[str, str], str], optional): Controls how- the model responds to function calls, as specified in the- creator's documentation.- kwargs (Optional[Dict[str, Any]]): The extra modifications to be- made on the original settings defined in :obj:`ChatGPTConfig`.-- Return:- FunctionCallingConfig: A new instance which loads the given- function list into a list of dictionaries and the input- :obj:`function_call` argument.- """- return cls(- functions=[- func.get_openai_function_schema() for func in function_list- ],- function_call=function_call,- **(kwargs or {}),- )+ def __post_init__(self):+ if self.tools is not None:+ object.__setattr__(+ self,+ 'tools',+ [tool.get_openai_tool_schema() for tool in self.tools],+ )OPENAI_API_PARAMS = {param for param in asdict(ChatGPTConfig()).keys()}-OPENAI_API_PARAMS_WITH_FUNCTIONS = {- param for param in asdict(FunctionCallingConfig()).keys()-}@dataclass(frozen=True)diff --git a/camel/functions/openai_function.py b/camel/functions/openai_function.pyindex e010f00bb..e5ee3a01c 100644--- a/camel/functions/openai_function.py+++ b/camel/functions/openai_function.py@@ -171,7 +171,6 @@ class OpenAIFunction:self.openai_tool_schema = openai_tool_schema or get_openai_tool_schema(func)- self.properties = self.openai_tool_schema@staticmethoddef validate_openai_tool_schema(openai_tool_schema: Dict[str, Any]) -> None:@@ -193,6 +192,9 @@ class OpenAIFunction:SchemaError: If the parameters do not meet JSON Schema referencespecifications."""+ # Check the type+ if not openai_tool_schema["type"]:+ raise ValueError("miss type")# Check the function descriptionif not openai_tool_schema["function"]["description"]:raise ValueError("miss function description")diff --git a/camel/models/openai_model.py b/camel/models/openai_model.pyindex 48d28e548..039b50a3e 100644--- a/camel/models/openai_model.py+++ b/camel/models/openai_model.py@@ -16,7 +16,7 @@ from typing import Any, Dict, List, Optional, Unionfrom openai import OpenAI, Stream-from camel.configs import OPENAI_API_PARAMS_WITH_FUNCTIONS+from camel.configs import OPENAI_API_PARAMSfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackendfrom camel.types import ChatCompletion, ChatCompletionChunk, ModelType@@ -86,7 +86,7 @@ class OpenAIModel(BaseModelBackend):unexpected arguments to OpenAI API."""for param in self.model_config_dict:- if param not in OPENAI_API_PARAMS_WITH_FUNCTIONS:+ if param not in OPENAI_API_PARAMS:raise ValueError(f"Unexpected argument `{param}` is ""input into OpenAI model backend."diff --git a/camel/utils/commons.py b/camel/utils/commons.pyindex 418525aa4..a0769cf54 100644--- a/camel/utils/commons.py+++ b/camel/utils/commons.py@@ -275,13 +275,13 @@ def role_playing_with_function("account infomation to create a tweet. Search basketball""course from coursera And help me to choose a basketball by klarna."),- function_list: Optional[List] = None,+ tools: Optional[List] = None,model_type=None,chat_turn_limit=10,assistant_role_name: str = "Searcher",user_role_name: str = "Professor",) -> None:- r"""Initializes and conducts a `RolePlaying` with `FunctionCallingConfig`+ r"""Initializes and conducts a `RolePlaying` with `ChatGPTConfig`session. The function creates an interactive and dynamic role-play sessionwhere the AI Assistant and User engage based on the given task, roles, andavailable functions. It demonstrates the versatility of AI in handling@@ -292,7 +292,7 @@ def role_playing_with_function(task_prompt (str): The initial task or scenario description to startthe `RolePlaying` session. Defaults to a prompt involving theestimation of KAUST's age and weather information.- function_list (list): A list of functions that the agent can utilize+ tools (list): A list of functions that the agent can utilizeduring the session. Defaults to a combination of math, search, andweather functions.model_type (ModelType): The type of chatbot model used for both the@@ -310,24 +310,23 @@ def role_playing_with_function("""# Run lazy import- if function_list is None:- function_list = get_lazy_imported_functions_module()+ if tools is None:+ tools = get_lazy_imported_functions_module()if model_type is None:model_type = get_lazy_imported_types_module()from colorama import Forefrom camel.agents.chat_agent import FunctionCallingRecord- from camel.configs import ChatGPTConfig, FunctionCallingConfig+ from camel.configs import ChatGPTConfigfrom camel.societies import RolePlayingtask_prompt = task_promptuser_model_config = ChatGPTConfig(temperature=0.0)- function_list = function_list- assistant_model_config = FunctionCallingConfig.from_openai_function_list(- function_list=function_list,- kwargs=dict(temperature=0.0),+ assistant_model_config = ChatGPTConfig(+ tools=tools,+ temperature=0.0,)role_play_session = RolePlaying(@@ -336,7 +335,7 @@ def role_playing_with_function(assistant_agent_kwargs=dict(model_type=model_type,model_config=assistant_model_config,- function_list=function_list,+ tools=tools,),user_agent_kwargs=dict(model_type=model_type,@@ -394,10 +393,10 @@ def role_playing_with_function(# Print output from the assistant, including any function# execution informationprint_text_animated(Fore.GREEN + "AI Assistant:")- called_functions: List[FunctionCallingRecord] = assistant_response.info[- 'called_functions'+ tool_calls: List[FunctionCallingRecord] = assistant_response.info[+ 'tool_calls']- for func_record in called_functions:+ for func_record in tool_calls:print_text_animated(f"{func_record}")print_text_animated(f"{assistant_response.msg.content}\n")diff --git a/docs/agents/single_agent.md b/docs/agents/single_agent.mdindex d3917d0dc..f367fd49f 100644--- a/docs/agents/single_agent.md+++ b/docs/agents/single_agent.md@@ -69,14 +69,14 @@ Woohoo, your first agent is ready to play with you!# Import the necessary functionsfrom camel.functions import MATH_FUNCS, SEARCH_FUNCS-# Initialize the agent with list of functions+# Initialize the agent with list of toolsagent = ChatAgent(system_message=sys_msg,- function_list=[*MATH_FUNCS, *SEARCH_FUNCS]+ tools=[*MATH_FUNCS, *SEARCH_FUNCS])-# Check if functions are enabled-agent.is_function_calling_enabled()+# Check if tools are enabled+agent.is_tools_added()>>> True```@@ -130,7 +130,7 @@ You can connect the agent with external database (as long-term memory) in whichagent = ChatAgent(sys_msg, **agent_kwargs)```-- The `ChatAgent` class offers several useful initialization options, including `model_type`, `model_config`, `memory`, `message_window_size`, `token_limit`, `output_language`, `function_list`, and `response_terminators`. Check [`chat_agent.py`](https://github.com/camel-ai/camel/blob/master/camel/agents/chat_agent.py) for detailed usage guidance.+- The `ChatAgent` class offers several useful initialization options, including `model_type`, `model_config`, `memory`, `message_window_size`, `token_limit`, `output_language`, `tools`, and `response_terminators`. Check [`chat_agent.py`](https://github.com/camel-ai/camel/blob/master/camel/agents/chat_agent.py) for detailed usage guidance.## Remarksdiff --git a/docs/tutorials_and_cookbooks/agents_with_rag.md b/docs/tutorials_and_cookbooks/agents_with_rag.mdindex 8e73a020d..89700884a 100644--- a/docs/tutorials_and_cookbooks/agents_with_rag.md+++ b/docs/tutorials_and_cookbooks/agents_with_rag.md@@ -245,7 +245,7 @@ role_playing_with_function(task_prompt=("What is the main termination reasons for AI Society dataset, how many number of messages did camel decided to limit, what's the value plus 100?"),- function_list=[*RETRIEVER_FUNCS, *MATH_FUNCS],+ tools=[*RETRIEVER_FUNCS, *MATH_FUNCS],)``````markdowndiff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.pyindex d2e8c3c4f..15102d12f 100644--- a/test/agents/test_chat_agent.py+++ b/test/agents/test_chat_agent.py@@ -23,7 +23,7 @@ from PIL import Imagefrom camel.agents import ChatAgentfrom camel.agents.chat_agent import FunctionCallingRecord-from camel.configs import ChatGPTConfig, FunctionCallingConfig+from camel.configs import ChatGPTConfigfrom camel.functions import MATH_FUNCSfrom camel.generators import SystemMessageGeneratorfrom camel.memories import MemoryRecord@@ -330,7 +330,7 @@ def test_token_exceed_return():"usage": None,"termination_reasons": ["max_tokens_exceeded"],"num_tokens": 1000,- "called_functions": [],+ "tool_calls": [],}agent.terminated = Trueresponse = agent.step_token_exceed(1000, [], "max_tokens_exceeded")@@ -347,9 +347,7 @@ def test_function_enabled():meta_dict=None,content="You are a help assistant.",)- model_config = FunctionCallingConfig(- functions=[func.get_openai_function_schema() for func in MATH_FUNCS]- )+ model_config = ChatGPTConfig(tools=[*MATH_FUNCS])agent_no_func = ChatAgent(system_message=system_message,model_config=model_config,@@ -359,29 +357,27 @@ def test_function_enabled():system_message=system_message,model_config=model_config,model_type=ModelType.GPT_4,- function_list=MATH_FUNCS,+ tools=MATH_FUNCS,)- assert not agent_no_func.is_function_calling_enabled()- assert agent_with_funcs.is_function_calling_enabled()+ assert not agent_no_func.is_tools_added()+ assert agent_with_funcs.is_tools_added()@pytest.mark.model_backend-def test_function_calling():+def test_tool_calling():system_message = BaseMessage(role_name="assistant",role_type=RoleType.ASSISTANT,meta_dict=None,content="You are a help assistant.",)- model_config = FunctionCallingConfig(- functions=[func.get_openai_function_schema() for func in MATH_FUNCS]- )+ model_config = ChatGPTConfig(tools=[*MATH_FUNCS])agent = ChatAgent(system_message=system_message,model_config=model_config,model_type=ModelType.GPT_4,- function_list=MATH_FUNCS,+ tools=MATH_FUNCS,)ref_funcs = MATH_FUNCS@@ -396,18 +392,16 @@ def test_function_calling():)agent_response = agent.step(user_msg)- called_funcs: List[FunctionCallingRecord] = agent_response.info[- 'called_functions'- ]- for called_func in called_funcs:+ tool_calls: List[FunctionCallingRecord] = agent_response.info['tool_calls']+ for called_func in tool_calls:print(str(called_func))- assert len(called_funcs) > 0- assert str(called_funcs[0]).startswith("Function Execution")+ assert len(tool_calls) > 0+ assert str(tool_calls[0]).startswith("Function Execution")- assert called_funcs[0].func_name == "mul"- assert called_funcs[0].args == {"a": 2, "b": 8}- assert called_funcs[0].result == 16+ assert tool_calls[0].func_name == "mul"+ assert tool_calls[0].args == {"a": 2, "b": 8}+ assert tool_calls[0].result == 16def test_response_words_termination():diff --git a/test/agents/test_role_playing.py b/test/agents/test_role_playing.pyindex 13c5b09ea..a645a49cf 100644--- a/test/agents/test_role_playing.py+++ b/test/agents/test_role_playing.py@@ -14,7 +14,7 @@import pytestfrom camel.agents import ChatAgent, CriticAgent-from camel.configs import FunctionCallingConfig+from camel.configs import ChatGPTConfigfrom camel.functions import MATH_FUNCSfrom camel.human import Humanfrom camel.messages import BaseMessage@@ -130,17 +130,15 @@ def test_role_playing_step(@pytest.mark.model_backenddef test_role_playing_with_function():- function_list = [*MATH_FUNCS]- assistant_model_config = FunctionCallingConfig.from_openai_function_list(- function_list=function_list- )+ tools = [*MATH_FUNCS]+ assistant_model_config = ChatGPTConfig(tools=tools)role_playing = RolePlaying(assistant_role_name="AI Assistant",assistant_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO,model_config=assistant_model_config,- function_list=function_list,+ tools=tools,),user_role_name="AI User",user_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO),diff --git a/test/models/test_open_source_model.py b/test/models/test_open_source_model.pyindex 50883691d..2c775541d 100644--- a/test/models/test_open_source_model.py+++ b/test/models/test_open_source_model.py@@ -17,7 +17,6 @@ import pytestfrom camel.configs import (ChatGPTConfig,- FunctionCallingConfig,OpenSourceConfig,)from camel.models import OpenSourceModel@@ -127,20 +126,19 @@ def test_open_source_model_unexpected_argument():model_config = OpenSourceConfig(model_path=model_path,server_url=DEFAULT_SERVER_URL,- api_params=FunctionCallingConfig(),+ api_params=ChatGPTConfig(),)model_config_dict = model_config.__dict__with pytest.raises(- ValueError,+ TypeError,match=re.escape(- (- "Unexpected argument `functions` is "- "input into open-source model backend."- )+ ("__init__() got an unexpected keyword argument 'unexpected_arg'")),):- _ = OpenSourceModel(model_type, model_config_dict)+ _ = OpenSourceModel(+ model_type, model_config_dict, unexpected_arg="unexpected_arg"+ )@pytest.mark.model_backend