🐫 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: Add Claude tool calling (#1799)
Xiaotian Jinf78e4e6b4368
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 3734dfe84..9452bb4df 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -699,12 +699,12 @@ class ChatAgent(BaseAgent):if not response and self.model_backend.num_models > 1:raise ModelProcessingError("Unable to process messages: none of the provided models "- "run succesfully."+ "run successfully.")elif not response:raise ModelProcessingError(f"Unable to process messages: the only provided model "- f"did not run succesfully. Error: {error_info}"+ f"did not run successfully. Error: {error_info}")logger.info(@@ -744,12 +744,12 @@ class ChatAgent(BaseAgent):if not response and self.model_backend.num_models > 1:raise ModelProcessingError("Unable to process messages: none of the provided models "- "run succesfully."+ "run successfully.")elif not response:raise ModelProcessingError(f"Unable to process messages: the only provided model "- f"did not run succesfully. Error: {error_info}"+ f"did not run successfully. Error: {error_info}")logger.info(diff --git a/camel/configs/anthropic_config.py b/camel/configs/anthropic_config.pyindex 828bdd3ed..678f14e27 100644--- a/camel/configs/anthropic_config.py+++ b/camel/configs/anthropic_config.py@@ -70,7 +70,6 @@ class AnthropicConfig(BaseConfig):stop_sequences: ClassVar[Union[List[str], NotGiven]] = []temperature: float = 1top_p: Union[float, NotGiven] = 0.7- top_k: Union[int, NotGiven] = 5stream: bool = Falsemetadata: Union[dict, NotGiven] = NotGiven()thinking: Union[dict, NotGiven] = NotGiven()diff --git a/camel/models/anthropic_model.py b/camel/models/anthropic_model.pyindex ac8517e31..552b84cdf 100644--- a/camel/models/anthropic_model.py+++ b/camel/models/anthropic_model.py@@ -35,13 +35,13 @@ class AnthropicModel(BaseModelBackend):model_type (Union[ModelType, str]): Model for which a backend iscreated, one of CLAUDE_* series.model_config_dict (Optional[Dict[str, Any]], optional): A dictionary- that will be fed into Anthropic.messages.create(). If+ that will be fed into `openai.ChatCompletion.create()`. If:obj:`None`, :obj:`AnthropicConfig().as_dict()` will be used.(default: :obj:`None`)api_key (Optional[str], optional): The API key for authenticating withthe Anthropic service. (default: :obj:`None`)url (Optional[str], optional): The url to the Anthropic service.- (default: :obj:`None`)+ (default: :obj:`https://api.anthropic.com/v1/`)token_counter (Optional[BaseTokenCounter], optional): Token counter touse for the model. If not provided, :obj:`AnthropicTokenCounter`will be used. (default: :obj:`None`)@@ -61,43 +61,24 @@ class AnthropicModel(BaseModelBackend):url: Optional[str] = None,token_counter: Optional[BaseTokenCounter] = None,) -> None:- from anthropic import Anthropic, AsyncAnthropic+ from openai import AsyncOpenAI, OpenAIif model_config_dict is None:model_config_dict = AnthropicConfig().as_dict()api_key = api_key or os.environ.get("ANTHROPIC_API_KEY")- url = url or os.environ.get("ANTHROPIC_API_BASE_URL")+ url = (+ url+ or os.environ.get("ANTHROPIC_API_BASE_URL")+ or "https://api.anthropic.com/v1/"+ )super().__init__(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- )+ self.client = OpenAI(base_url=self._url, api_key=self._api_key)- def _convert_response_from_anthropic_to_openai(self, response):- # openai ^1.0.0 format, reference openai/types/chat/chat_completion.py- obj = ChatCompletion.construct(- id=None,- choices=[- dict(- index=0,- message={- "role": "assistant",- "content": next(- content.text- for content in response.content- if content.type == "text"- ),- },- finish_reason=response.stop_reason,- )- ],- created=None,- model=response.model,- object="chat.completion",+ self.async_client = AsyncOpenAI(+ api_key=self._api_key, base_url=self._url)- return obj@propertydef token_counter(self) -> BaseTokenCounter:@@ -126,22 +107,13 @@ class AnthropicModel(BaseModelBackend):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 = self.client.messages.create(+ response = self.client.chat.completions.create(model=self.model_type,- system=sys_msg,- messages=messages, # type: ignore[arg-type]+ messages=messages,**self.model_config_dict,+ tools=tools, # type: ignore[arg-type])- # format response to openai format- response = self._convert_response_from_anthropic_to_openai(response)-return responseasync def _arun(@@ -159,21 +131,14 @@ class AnthropicModel(BaseModelBackend):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(+ response = await self.async_client.chat.completions.create(model=self.model_type,- system=sys_msg,- messages=messages, # type: ignore[arg-type]+ messages=messages,**self.model_config_dict,+ tools=tools, # type: ignore[arg-type])- # format response to openai format- return self._convert_response_from_anthropic_to_openai(response)+ return responsedef check_model_config(self):r"""Check whether the model configuration is valid for anthropic@@ -181,8 +146,7 @@ class AnthropicModel(BaseModelBackend):Raises:ValueError: If the model configuration dictionary contains any- unexpected arguments to OpenAI API, or it does not contain- :obj:`model_path` or :obj:`server_url`.+ unexpected arguments to Anthropic API."""for param in self.model_config_dict:if param not in ANTHROPIC_API_PARAMS:diff --git a/examples/models/anthiropic_model_example.py b/examples/models/anthiropic_model_example.pyindex 3cf63bffe..7a2ca9517 100644--- a/examples/models/anthiropic_model_example.py+++ b/examples/models/anthiropic_model_example.py@@ -136,3 +136,47 @@ The script works by:3. Creating the transpose by iterating through columns first, then rows4. Formatting the result with proper brackets and commas''' # noqa: E501++# Tool calling+from camel.agents import ChatAgent # noqa: E402+from camel.configs import AnthropicConfig # noqa: E402+from camel.models import ModelFactory # noqa: E402+from camel.toolkits import FunctionTool # noqa: E402+from camel.types import ModelPlatformType, ModelType # noqa: E402+++def my_add(a: int, b: int) -> int:+ """Add two numbers together and return the result."""+ return a + b+++anthropic_model = ModelFactory.create(+ model_platform=ModelPlatformType.ANTHROPIC,+ model_type=ModelType.CLAUDE_3_5_SONNET,+ model_config_dict=AnthropicConfig(temperature=0.2).as_dict(),+)++anthropic_agent = ChatAgent(+ model=anthropic_model,+ tools=[FunctionTool(my_add)],+)++print("Testing Anthropic agent with tool calling:")+user_msg = "Use the tool my_add to calculate 2 + 2"+response = anthropic_agent.step(user_msg)+print(response.msgs[0].content)+"""+The result of adding 2 + 2 is 4.+"""++# Check if tool was called+if response.info and response.info.get("tool_calls"):+ print("Tool was called successfully!")+ print(f"Tool calls: {response.info['tool_calls']}")+else:+ print("No tool calls were made.")++"""+Tool was called successfully!+Tool calls: [ToolCallingRecord(tool_name='my_add', args={'a': 2, 'b': 2}, result=4, tool_call_id='toolu_01L1KV8GZtMEyHUGTudpMg5g')]+""" # noqa: E501