🐫 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
feat: structure response using function call (#778)
Raya632b09d5da9
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 65ed3c764..6a512f138 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -18,6 +18,8 @@ from collections import defaultdictfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple+from pydantic import BaseModel+from camel.agents.base import BaseAgentfrom camel.configs import ChatGPTConfigfrom camel.memories import (@@ -29,6 +31,7 @@ from camel.memories import (from camel.messages import BaseMessage, FunctionCallingMessage, OpenAIMessagefrom camel.models import BaseModelBackend, ModelFactoryfrom camel.responses import ChatAgentResponse+from camel.toolkits import OpenAIFunctionfrom camel.types import (ChatCompletion,ChatCompletionChunk,@@ -37,13 +40,18 @@ from camel.types import (OpenAIBackendRole,RoleType,)-from camel.utils import get_model_encoding+from camel.utils import (+ Constants,+ func_string_to_callable,+ get_model_encoding,+ get_pydantic_object_schema,+ json_to_function_code,+)if TYPE_CHECKING:from openai import Streamfrom camel.terminators import ResponseTerminator- from camel.toolkits import OpenAIFunction@dataclass(frozen=True)@@ -287,6 +295,7 @@ class ChatAgent(BaseAgent):def step(self,input_message: BaseMessage,+ output_schema: Optional[BaseModel] = None,) -> ChatAgentResponse:r"""Performs a single step in the chat session by generating a responseto the input message.@@ -297,6 +306,10 @@ class ChatAgent(BaseAgent):either `user` or `assistant` but it will be set to `user`anyway since for the self agent any incoming message isexternal.+ output_schema (Optional[BaseModel]): An optional pydantic model+ that includes value types and field descriptions used to+ generate a structured response by LLM. This schema helps+ in defining the expected output format.Returns:ChatAgentResponse: A struct containing the output messages,@@ -318,6 +331,15 @@ class ChatAgent(BaseAgent):return self.step_token_exceed(e.args[1], tool_calls, "max_tokens_exceeded")+ # use structed output response without tools+ # If the user provides the output_schema parameter and does not+ # specify the use of tools, then in the model config of the+ # chatgent, call the model specified by tools with+ # return_json_response of OpenAIFunction format, and return a+ # structured response with the user-specified output schema.+ if output_schema is not None and len(self.func_dict) == 0:+ self._add_output_schema_to_tool_list(output_schema)+(response,output_messages,@@ -333,9 +355,8 @@ class ChatAgent(BaseAgent):):# Tools added for function calling and not in stream mode- # Do function calling- func_assistant_msg, func_result_msg, func_record = (- self.step_tool_call(response)+ tool_calls, func_assistant_msg, func_result_msg = (+ self._add_tools_for_func_call(response, tool_calls))# Update the messages@@ -344,11 +365,44 @@ class ChatAgent(BaseAgent):)self.update_memory(func_result_msg, OpenAIBackendRole.FUNCTION)- # Record the function calling- tool_calls.append(func_record)-else:- # Function calling disabled or not a function calling+ # If the user specifies tools, it is necessary to wait for the+ # model to complete all tools' calls. Finally, use the+ # generated response as the input for the structure,+ # simultaneously calling the return_json_response function.+ # Call the model again with return_json_response in the format+ # of OpenAIFunction as the last tool, returning a structured+ # response with the user-specified output schema.+ if output_schema is not None and all(+ record.func_name+ != Constants.FUNC_NAME_FOR_STRUCTURE_OUTPUT+ for record in tool_calls+ ):+ self._add_output_schema_to_tool_list(output_schema)++ (+ response,+ output_messages,+ finish_reasons,+ usage_dict,+ response_id,+ ) = self._step_model_response(openai_messages, num_tokens)++ if isinstance(response, ChatCompletion):+ # Tools added for function calling and not in stream+ # mode+ tool_calls, func_assistant_msg, func_result_msg = (+ self._add_tools_for_func_call(response, tool_calls)+ )++ # Update the messages+ self.update_memory(+ func_assistant_msg, OpenAIBackendRole.ASSISTANT+ )+ self.update_memory(+ func_result_msg, OpenAIBackendRole.FUNCTION+ )+info = self._step_get_info(output_messages,finish_reasons,@@ -359,20 +413,32 @@ class ChatAgent(BaseAgent):)break+ # if use structure response, set structure result as content of+ # BaseMessage+ if output_schema and self.model_type.is_openai:+ for base_message_item in output_messages:+ base_message_item.content = str(info['tool_calls'][-1].result)+return ChatAgentResponse(output_messages, self.terminated, info)async def step_async(self,input_message: BaseMessage,+ output_schema: Optional[BaseModel] = None,) -> ChatAgentResponse:r"""Performs a single step in the chat session by generating a responseto the input message. This agent step can call async function calls.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.+ output_schema (Optional[BaseModel]): An optional pydantic model+ that includes value types and field descriptions used to+ generate a structured response by LLM. This schema helps+ in defining the expected output format.Returns:ChatAgentResponse: A struct containing the output messages,@@ -394,6 +460,9 @@ class ChatAgent(BaseAgent):return self.step_token_exceed(e.args[1], tool_calls, "max_tokens_exceeded")+ if output_schema is not None:+ self._add_output_schema_to_tool_list(output_schema)+(response,output_messages,@@ -426,6 +495,37 @@ class ChatAgent(BaseAgent):tool_calls.append(func_record)else:+ # use structed output response without tools+ if output_schema is not None and all(+ record.func_name+ != Constants.FUNC_NAME_FOR_STRUCTURE_OUTPUT+ for record in tool_calls+ ):+ self._add_output_schema_to_tool_list(output_schema)++ (+ response,+ output_messages,+ finish_reasons,+ usage_dict,+ response_id,+ ) = self._step_model_response(openai_messages, num_tokens)++ if isinstance(response, ChatCompletion):+ # Tools added for function calling and not in stream+ # mode+ tool_calls, func_assistant_msg, func_result_msg = (+ self._add_tools_for_func_call(response, tool_calls)+ )++ # Update the messages+ self.update_memory(+ func_assistant_msg, OpenAIBackendRole.ASSISTANT+ )+ self.update_memory(+ func_result_msg, OpenAIBackendRole.FUNCTION+ )+# Function calling disabled or not a function callinginfo = self._step_get_info(output_messages,@@ -437,8 +537,88 @@ class ChatAgent(BaseAgent):)break+ # if use structure response, set structure result as content of+ # BaseMessage+ if output_schema and self.model_type.is_openai:+ for base_message_item in output_messages:+ base_message_item.content = str(info['tool_calls'][0].result)+return ChatAgentResponse(output_messages, self.terminated, info)+ def _add_tools_for_func_call(+ self,+ response: ChatCompletion,+ tool_calls: List[FunctionCallingRecord],+ ) -> tuple[+ List[FunctionCallingRecord],+ FunctionCallingMessage,+ FunctionCallingMessage,+ ]:+ r"""+ Handles adding tools for function calls based on the response.+ This method processes a function call within the chat completion+ response, and records the function call in the provided+ list of tool calls.+ Args:+ response (ChatCompletion): The response object from the chat+ completion.+ tool_calls (List[FunctionCallingRecord]): The list to record+ function calls.+ Returns:+ tuple: A tuple containing:+ - List[FunctionCallingRecord]: The updated list of function+ call records.+ - FunctionCallingMessage: The assistant's message regarding the+ function call.+ - FunctionCallingMessage: The result message of the function+ call.+ """++ # Perform function calling+ func_assistant_msg, func_result_msg, func_record = self.step_tool_call(+ response+ )++ # Record the function call in the list of tool calls+ tool_calls.append(func_record)++ # Return updated tool calls list, assistant's message, and function+ # result message+ return tool_calls, func_assistant_msg, func_result_msg++ def _add_output_schema_to_tool_list(self, output_schema: BaseModel):+ r"""Handles the structured output response for OpenAI.+ This method processes the given output schema and integrates the+ resulting function into the tools for the OpenAI model configuration.+ Args:+ output_schema (BaseModel): The schema representing the expected+ output structure.+ """++ # step 1 extract the output_schema info as json.+ schema_json = get_pydantic_object_schema(output_schema)++ # step 2 convert output schema json as callable string+ func_str = json_to_function_code(schema_json)++ # step 3 get callable function from string+ func_callable = func_string_to_callable(func_str)++ # step 4 add return_json_func into tools+ func = OpenAIFunction(func_callable)+ tools = [func]+ self.func_dict[func.get_function_name()] = func.func+ if self.model_type.is_openai:+ self.model_backend.model_config_dict = ChatGPTConfig(+ tools=tools+ ).__dict__+ elif self.model_type.is_gemini:+ from camel.configs.gemini_config import GeminiConfig++ self.model_backend.model_config_dict = GeminiConfig(+ tools=tools+ ).__dict__+def _step_model_response(self,openai_messages: list[OpenAIMessage],diff --git a/camel/agents/embodied_agent.py b/camel/agents/embodied_agent.pyindex bdb0d6a33..88285c288 100644--- a/camel/agents/embodied_agent.py+++ b/camel/agents/embodied_agent.py@@ -120,10 +120,8 @@ class EmbodiedAgent(ChatAgent):else:return []- def step(- self,- input_message: BaseMessage,- ) -> ChatAgentResponse:+ # ruff: noqa: E501+ def step(self, input_message: BaseMessage) -> ChatAgentResponse: # type: ignore[override]r"""Performs a step in the conversation.Args:diff --git a/camel/toolkits/google_maps_toolkit.py b/camel/toolkits/google_maps_toolkit.pyindex 82cbc2bb0..7abbad4aa 100644--- a/camel/toolkits/google_maps_toolkit.py+++ b/camel/toolkits/google_maps_toolkit.py@@ -36,7 +36,8 @@ def handle_googlemaps_exceptions(@wraps(func)def wrapper(*args: Any, **kwargs: Any) -> Any:try:- from googlemaps.exceptions import ( # type: ignore[import-untyped] # isort: skip+ # ruff: noqa: E501+ from googlemaps.exceptions import ( # type: ignore[import]ApiError,HTTPError,Timeout,diff --git a/camel/toolkits/openai_function.py b/camel/toolkits/openai_function.pyindex ec810a23d..e2b35a884 100644--- a/camel/toolkits/openai_function.py+++ b/camel/toolkits/openai_function.py@@ -20,7 +20,7 @@ from jsonschema.validators import Draft202012Validator as JSONValidatorfrom pydantic import create_modelfrom pydantic.fields import FieldInfo-from camel.utils import PYDANTIC_V2, to_pascal+from camel.utils import get_pydantic_object_schema, to_pascaldef _remove_a_key(d: Dict, remove_key: Any) -> None:@@ -110,12 +110,7 @@ def get_openai_tool_schema(func: Callable) -> Dict[str, Any]:return create_model(name, **field)model = _create_mol(to_pascal(func.__name__), fields)- # NOTE: Method `.schema()` is deprecated in pydantic v2.- # the result would be identical to `.model_json_schema()` in v2- if PYDANTIC_V2:- parameters_dict = model.model_json_schema()- else:- parameters_dict = model.schema()+ parameters_dict = get_pydantic_object_schema(model)# The `"title"` is generated by `model.model_json_schema()`# but is useless for openai json schema_remove_a_key(parameters_dict, "title")diff --git a/camel/utils/__init__.py b/camel/utils/__init__.pyindex 91d0bceee..26ce7aa05 100644--- a/camel/utils/__init__.py+++ b/camel/utils/__init__.py@@ -13,17 +13,20 @@# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========from .commons import (- PYDANTIC_V2,api_keys_required,check_server_running,create_chunks,dependencies_required,download_tasks,+ func_string_to_callable,get_first_int,get_prompt_template_key_words,+ get_pydantic_major_version,+ get_pydantic_object_schema,get_system_information,get_task_list,is_docker_running,+ json_to_function_code,print_text_animated,text_extract_from_web,to_pascal,@@ -50,7 +53,6 @@ __all__ = ['AnthropicTokenCounter','get_system_information','to_pascal',- 'PYDANTIC_V2','get_model_encoding','BaseTokenCounter','OpenAITokenCounter',@@ -64,4 +66,8 @@ __all__ = ['is_docker_running','GeminiTokenCounter','MistralTokenCounter',+ 'get_pydantic_major_version',+ 'get_pydantic_object_schema',+ 'func_string_to_callable',+ 'json_to_function_code',]diff --git a/camel/utils/commons.py b/camel/utils/commons.pyindex 7deac6b66..5432862a2 100644--- a/camel/utils/commons.py+++ b/camel/utils/commons.py@@ -20,14 +20,27 @@ import subprocessimport timeimport zipfilefrom functools import wraps-from typing import Any, Callable, List, Optional, Set, TypeVar, cast+from typing import (+ Any,+ Callable,+ Dict,+ List,+ Mapping,+ Optional,+ Set,+ TypeVar,+ cast,+)from urllib.parse import urlparseimport pydanticimport requests+from pydantic import BaseModelfrom camel.types import TaskType+from .constants import Constants+F = TypeVar('F', bound=Callable[..., Any])@@ -303,7 +316,97 @@ def to_pascal(snake: str) -> str:)-PYDANTIC_V2 = pydantic.VERSION.startswith("2.")+def get_pydantic_major_version() -> int:+ r"""Get the major version of Pydantic.++ Returns:+ int: The major version number of Pydantic if installed, otherwise 0.+ """+ try:+ return int(pydantic.__version__.split(".")[0])+ except ImportError:+ return 0+++def get_pydantic_object_schema(pydantic_params: BaseModel) -> Dict:+ r"""Get the JSON schema of a Pydantic model.++ Args:+ pydantic_params (BaseModel): The Pydantic model to retrieve the schema+ for.++ Returns:+ dict: The JSON schema of the Pydantic model.+ """+ return pydantic_params.model_json_schema()+++def func_string_to_callable(code: str):+ r"""Convert a function code string to a callable function object.++ Args:+ code (str): The function code as a string.++ Returns:+ Callable[..., Any]: The callable function object extracted from the+ code string.+ """+ local_vars: Mapping[str, object] = {}+ exec(code, globals(), local_vars)+ func = local_vars.get(Constants.FUNC_NAME_FOR_STRUCTURE_OUTPUT)+ return func+++def json_to_function_code(json_obj: Dict) -> str:+ r"""Generate a Python function code from a JSON schema.++ Args:+ json_obj (dict): The JSON schema object containing properties and+ required fields, and json format is follow openai tools schema++ Returns:+ str: The generated Python function code as a string.+ """+ properties = json_obj.get('properties', {})+ required = json_obj.get('required', [])++ if not properties or not required:+ raise ValueError(+ "JSON schema must contain 'properties' and 'required' fields"+ )++ args = []+ docstring_args = []+ return_keys = []++ for prop in required:+ description = properties[prop]['description']+ prop_type = properties[prop]['type']+ python_type = 'str' if prop_type == 'string' else prop_type+ args.append(f"{prop}: {python_type}")+ docstring_args.append(+ f" {prop} ({python_type}): {description}."+ )+ return_keys.append(prop)++ # extract entity of schema+ args_str = ", ".join(args)+ docstring_args_str = "\n".join(docstring_args)+ return_keys_str = ", ".join(return_keys)++ # function template+ function_code = f'''+def {Constants.FUNC_NAME_FOR_STRUCTURE_OUTPUT}({args_str}):+ r"""Return response with a specified json format.+ Args:+{docstring_args_str}+ Returns:+ Dict: A dictionary containing {return_keys_str}.+ """+ return {{{", ".join([f'"{prop}": {prop}' for prop in required])}}}+ '''++ return function_codedef text_extract_from_web(url: str) -> str:diff --git a/camel/utils/constants.py b/camel/utils/constants.pyindex a5d969acb..65f548f35 100644--- a/camel/utils/constants.py+++ b/camel/utils/constants.py@@ -24,3 +24,6 @@ class Constants:# default plug of imageio to read videoVIDEO_DEFAULT_PLUG_PYAV = "pyav"++ # return response with json format+ FUNC_NAME_FOR_STRUCTURE_OUTPUT = "return_json_response"diff --git a/examples/structured_response/json_format_reponse_with_tools.py b/examples/structured_response/json_format_reponse_with_tools.pynew file mode 100644index 000000000..35dc95ffb--- /dev/null+++ b/examples/structured_response/json_format_reponse_with_tools.py@@ -0,0 +1,76 @@+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========++from pydantic import BaseModel, Field++from camel.agents import ChatAgent+from camel.configs.openai_config import ChatGPTConfig+from camel.messages import BaseMessage+from camel.models import ModelFactory+from camel.toolkits import (+ MATH_FUNCS,+ SEARCH_FUNCS,+)+from camel.types import ModelPlatformType, ModelType++function_list = [+ *MATH_FUNCS,+ *SEARCH_FUNCS,+]+assistant_model_config = ChatGPTConfig(+ tools=function_list,+ temperature=0.0,+)++# Define system message+assistant_sys_msg = BaseMessage.make_assistant_message(+ role_name="Assistant",+ content="You are a helpful assistant.",+)++model = ModelFactory.create(+ model_platform=ModelPlatformType.OPENAI,+ model_type=ModelType.GPT_4O_MINI,+ model_config_dict=assistant_model_config.__dict__,+)++# Set agent+camel_agent = ChatAgent(+ assistant_sys_msg,+ model=model,+ tools=function_list,+)+++# pydantic basemodel as input params format+class Schema(BaseModel):+ current_age: str = Field(+ description=" the current age of University of Oxford"+ )+ calculated_age: str = Field(description="the add more years of age")+++user_msg = BaseMessage.make_user_message(+ role_name="User",+ content="Assume now is 2024 in the Gregorian calendar, "+ + "estimate the current age of University of Oxford "+ + "and then add 10 more years to this age, ",+)++# Get response information+response = camel_agent.step(user_msg, output_schema=Schema)+print(response.msgs[0].content)+"""+{'current_age': '928', 'calculated_age': '938'}+"""diff --git a/examples/structured_response/json_format_response.py b/examples/structured_response/json_format_response.pynew file mode 100644index 000000000..b2039dcda--- /dev/null+++ b/examples/structured_response/json_format_response.py@@ -0,0 +1,56 @@+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========++from pydantic import BaseModel, Field++from camel.agents import ChatAgent+from camel.configs.openai_config import ChatGPTConfig+from camel.messages import BaseMessage+from camel.models import ModelFactory+from camel.types import ModelPlatformType, ModelType++# Define system message+assistant_sys_msg = BaseMessage.make_assistant_message(+ role_name="Assistant",+ content="You are a helpful assistant.",+)++model = ModelFactory.create(+ model_platform=ModelPlatformType.OPENAI,+ model_type=ModelType.GPT_4O_MINI,+ model_config_dict=ChatGPTConfig().__dict__,+)++# Set agent+camel_agent = ChatAgent(assistant_sys_msg, model=model)+++# pydantic basemodel as input params format+class JokeResponse(BaseModel):+ joke: str = Field(description="a joke")+ funny_level: str = Field(description="Funny level, from 1 to 10")+++user_msg = BaseMessage.make_user_message(+ role_name="User",+ content="Tell a jokes.",+)++# Get response information+response = camel_agent.step(user_msg, output_schema=JokeResponse)+print(response.msgs[0].content)+"""+{'joke': "Why couldn't the bicycle find its way home? It lost its bearings!"+, 'funny_level': '8'}+"""diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.pyindex 60b64bc3f..32e26a461 100644--- a/test/agents/test_chat_agent.py+++ b/test/agents/test_chat_agent.py@@ -11,6 +11,7 @@# See the License for the specific language governing permissions and# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========+import astimport asynciofrom io import BytesIOfrom typing import List@@ -21,6 +22,7 @@ from openai.types.chat.chat_completion import Choicefrom openai.types.chat.chat_completion_message import ChatCompletionMessagefrom openai.types.completion_usage import CompletionUsagefrom PIL import Image+from pydantic import BaseModel, Fieldfrom camel.agents import ChatAgentfrom camel.agents.chat_agent import FunctionCallingRecord@@ -114,6 +116,45 @@ def test_chat_agent_stored_messages():assert context == expected_context[email protected]_backend+def test_chat_agent_step_with_structure_response():+ system_msg = BaseMessage(+ role_name="assistant",+ role_type=RoleType.ASSISTANT,+ meta_dict=None,+ content="You are a help assistant.",+ )+ assistant = ChatAgent(+ system_message=system_msg,+ )++ class JokeResponse(BaseModel):+ joke: str = Field(description="a joke")+ funny_level: str = Field(description="Funny level, from 1 to 10")++ user_msg = BaseMessage.make_user_message(+ role_name="User",+ content="Tell a jokes.",+ )++ response = assistant.step(user_msg, output_schema=JokeResponse)+ response_content_json = ast.literal_eval(response.msgs[0].content)+ joke_response_keys = set(+ JokeResponse.model_json_schema()["properties"].keys()+ )++ response_content_keys = set(response_content_json.keys())++ assert joke_response_keys.issubset(+ response_content_keys+ ), f"Missing keys: {joke_response_keys - response_content_keys}"++ for key in joke_response_keys:+ assert (+ key in response_content_json+ ), f"Key {key} not found in response content"++@pytest.mark.model_backenddef test_chat_agent_messages_window():system_msg = BaseMessage(diff --git a/test/toolkits/test_openai_function.py b/test/toolkits/test_openai_function.pyindex e6f16ed2f..75561b603 100644--- a/test/toolkits/test_openai_function.py+++ b/test/toolkits/test_openai_function.py@@ -21,7 +21,7 @@ from jsonschema.exceptions import SchemaErrorfrom camel.toolkits import OpenAIFunction, get_openai_tool_schemafrom camel.types import RoleType-from camel.utils import PYDANTIC_V2+from camel.utils import get_pydantic_major_versiondef test_get_openai_tool_schema():@@ -180,8 +180,9 @@ def test_get_openai_tool_schema():}openai_tool_schema = get_openai_tool_schema(test_all_parameters)+ pydantic_version = get_pydantic_major_version()- if PYDANTIC_V2:+ if pydantic_version == 2:assert openai_tool_schema == expect_res_v2else:assert openai_tool_schema == expect_res_v1