🐫 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: adding support for openrouter (#1917)
JINO ROHIT6a39c1adec14
diff --git a/camel/configs/__init__.py b/camel/configs/__init__.pyindex d52c35608..22ff9c3ac 100644--- a/camel/configs/__init__.py+++ b/camel/configs/__init__.py@@ -25,6 +25,7 @@ from .moonshot_config import MOONSHOT_API_PARAMS, MoonshotConfigfrom .nvidia_config import NVIDIA_API_PARAMS, NvidiaConfigfrom .ollama_config import OLLAMA_API_PARAMS, OllamaConfigfrom .openai_config import OPENAI_API_PARAMS, ChatGPTConfig+from .openrouter_config import OPENROUTER_API_PARAMS, OpenRouterConfigfrom .qwen_config import QWEN_API_PARAMS, QwenConfigfrom .reka_config import REKA_API_PARAMS, RekaConfigfrom .samba_config import (@@ -88,4 +89,6 @@ __all__ = ['SILICONFLOW_API_PARAMS','AIMLConfig','AIML_API_PARAMS',+ 'OpenRouterConfig',+ 'OPENROUTER_API_PARAMS',]diff --git a/camel/configs/openrouter_config.py b/camel/configs/openrouter_config.pynew file mode 100644index 000000000..15da70c87--- /dev/null+++ b/camel/configs/openrouter_config.py@@ -0,0 +1,106 @@+# ========= 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 __future__ import annotations++from typing import Optional, Sequence, Union++from camel.configs.base_config import BaseConfig+from camel.types import NotGiven+++class OpenRouterConfig(BaseConfig):+ r"""Defines the parameters for generating chat completions using OpenAI+ compatibility.++ Reference: https://openrouter.ai/docs/api-reference/parameters++ Args:+ temperature (float, optional): Sampling temperature to use, between+ :obj:`0` and :obj:`2`. Higher values make the output more random,+ while lower values make it more focused and deterministic.+ (default: :obj: `None`)+ top_p (float, optional): An alternative to sampling with temperature,+ called nucleus sampling, where the model considers the results of+ the tokens with top_p probability mass. So :obj:`0.1` means only+ the tokens comprising the top 10% probability mass are considered.+ (default: :obj: `None`)+ n (int, optional): How many chat completion choices to generate for+ each input message. (default: :obj: `None`)+ response_format (object, optional): An object specifying the format+ that the model must output. Compatible with GPT-4 Turbo and all+ GPT-3.5 Turbo models newer than gpt-3.5-turbo-1106. Setting to+ {"type": "json_object"} enables JSON mode, which guarantees the+ message the model generates is valid JSON. Important: when using+ JSON mode, you must also instruct the model to produce JSON+ yourself via a system or user message. Without this, the model+ may generate an unending stream of whitespace until the generation+ reaches the token limit, resulting in a long-running and seemingly+ "stuck" request. Also note that the message content may be+ partially cut off if finish_reason="length", which indicates the+ generation exceeded max_tokens or the conversation exceeded the+ max context length.+ stream (bool, optional): If True, partial message deltas will be sent+ as data-only server-sent events as they become available.+ (default: :obj: `None`)+ stop (str or list, optional): Up to :obj:`4` sequences where the API+ will stop generating further tokens. (default: :obj:`None`)+ max_tokens (int, optional): The maximum number of tokens to generate+ in the chat completion. The total length of input tokens and+ generated tokens is limited by the model's context length.+ (default: :obj:`None`)+ presence_penalty (float, optional): Number between :obj:`-2.0` and+ :obj:`2.0`. Positive values penalize new tokens based on whether+ they appear in the text so far, increasing the model's likelihood+ to talk about new topics. See more information about frequency and+ presence penalties. (default: :obj: `None`)+ frequency_penalty (float, optional): Number between :obj:`-2.0` and+ :obj:`2.0`. Positive values penalize new tokens based on their+ existing frequency in the text so far, decreasing the model's+ likelihood to repeat the same line verbatim. See more information+ about frequency and presence penalties. (default: :obj: `None`)+ user (str, optional): A unique identifier representing your end-user,+ which can help OpenAI to monitor and detect abuse.+ (default: :obj: `None`)+ tools (list[FunctionTool], 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. (default: :obj: `None`)+ 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. (default: :obj: `None`)+ """++ temperature: Optional[float] = None+ top_p: Optional[float] = None+ n: Optional[int] = None+ stream: Optional[bool] = None+ stop: Optional[Union[str, Sequence[str], NotGiven]] = None+ max_tokens: Optional[Union[int, NotGiven]] = None+ presence_penalty: Optional[float] = None+ response_format: Optional[Union[dict, NotGiven]] = None+ frequency_penalty: Optional[float] = None+ user: Optional[str] = None+ tool_choice: Optional[Union[dict[str, str], str]] = None+++OPENROUTER_API_PARAMS = {+ param for param in OpenRouterConfig.model_fields.keys()+}diff --git a/camel/models/__init__.py b/camel/models/__init__.pyindex 4d539ce61..fa71d4380 100644--- a/camel/models/__init__.py+++ b/camel/models/__init__.py@@ -33,6 +33,7 @@ from .ollama_model import OllamaModelfrom .openai_audio_models import OpenAIAudioModelsfrom .openai_compatible_model import OpenAICompatibleModelfrom .openai_model import OpenAIModel+from .openrouter_model import OpenRouterModelfrom .qwen_model import QwenModelfrom .reka_model import RekaModelfrom .samba_model import SambaModel@@ -48,6 +49,7 @@ from .zhipuai_model import ZhipuAIModel__all__ = ['BaseModelBackend','OpenAIModel',+ 'OpenRouterModel','AzureOpenAIModel','AnthropicModel','MistralModel',diff --git a/camel/models/model_factory.py b/camel/models/model_factory.pyindex 3f0337c47..dab4a7bd5 100644--- a/camel/models/model_factory.py+++ b/camel/models/model_factory.py@@ -29,6 +29,7 @@ from camel.models.nvidia_model import NvidiaModelfrom camel.models.ollama_model import OllamaModelfrom camel.models.openai_compatible_model import OpenAICompatibleModelfrom camel.models.openai_model import OpenAIModel+from camel.models.openrouter_model import OpenRouterModelfrom camel.models.qwen_model import QwenModelfrom camel.models.reka_model import RekaModelfrom camel.models.samba_model import SambaModel@@ -119,6 +120,8 @@ class ModelFactory:model_class = AnthropicModelelif model_platform.is_groq and model_type.is_groq:model_class = GroqModel+ elif model_platform.is_openrouter and model_type.is_openrouter:+ model_class = OpenRouterModelelif model_platform.is_zhipuai and model_type.is_zhipuai:model_class = ZhipuAIModelelif model_platform.is_gemini and model_type.is_gemini:diff --git a/camel/models/openrouter_model.py b/camel/models/openrouter_model.pynew file mode 100644index 000000000..e91ac00cf--- /dev/null+++ b/camel/models/openrouter_model.py@@ -0,0 +1,204 @@+# ========= 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 os+from typing import Any, Dict, List, Optional, Type, Union++from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream+from pydantic import BaseModel++from camel.configs import OPENROUTER_API_PARAMS, OpenRouterConfig+from camel.messages import OpenAIMessage+from camel.models import BaseModelBackend+from camel.models._utils import try_modify_message_with_format+from camel.types import (+ ChatCompletion,+ ChatCompletionChunk,+ ModelType,+)+from camel.utils import (+ BaseTokenCounter,+ OpenAITokenCounter,+ api_keys_required,+)+++class OpenRouterModel(BaseModelBackend):+ r"""LLM API served by OpenRouter in a unified BaseModelBackend interface.++ Args:+ model_type (Union[ModelType, str]): Model for which a backend is+ created.+ model_config_dict (Optional[Dict[str, Any]], optional): A dictionary+ that will be fed into:obj:`openai.ChatCompletion.create()`.+ If:obj:`None`, :obj:`GroqConfig().as_dict()` will be used.+ (default: :obj:`None`)+ api_key (Optional[str], optional): The API key for authenticating+ with the OpenRouter service. (default: :obj:`None`).+ url (Optional[str], optional): The url to the OpenRouter service.+ (default: :obj:`None`)+ token_counter (Optional[BaseTokenCounter], optional): Token counter to+ use for the model. If not provided, :obj:`OpenAITokenCounter(+ ModelType.GPT_4O_MINI)` will be used.+ (default: :obj:`None`)+ """++ @api_keys_required([("api_key", "OPENROUTER_API_KEY")])+ def __init__(+ self,+ model_type: Union[ModelType, str],+ model_config_dict: Optional[Dict[str, Any]] = None,+ api_key: Optional[str] = None,+ url: Optional[str] = None,+ token_counter: Optional[BaseTokenCounter] = None,+ ) -> None:+ if model_config_dict is None:+ model_config_dict = OpenRouterConfig().as_dict()+ api_key = api_key or os.environ.get("OPENROUTER_API_KEY")+ url = url or os.environ.get(+ "OPENROUTER_API_BASE_URL", "https://openrouter.ai/api/v1"+ )+ super().__init__(+ model_type, model_config_dict, api_key, url, token_counter+ )+ self._client = OpenAI(+ timeout=180,+ max_retries=3,+ 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,+ )++ @property+ def token_counter(self) -> BaseTokenCounter:+ r"""Initialize the token counter for the model backend.++ Returns:+ BaseTokenCounter: The token counter following the model's+ tokenization style.+ """+ if not self._token_counter:+ self._token_counter = OpenAITokenCounter(ModelType.GPT_4O_MINI)+ return self._token_counter++ def _prepare_request(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Dict[str, Any]:+ request_config = self.model_config_dict.copy()+ if tools:+ request_config["tools"] = tools+ elif response_format:+ try_modify_message_with_format(messages[-1], response_format)+ request_config["response_format"] = {"type": "json_object"}++ return request_config++ def _run(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ r"""Runs inference of OpenAI chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.+ response_format (Optional[Type[BaseModel]]): The format of the+ response.+ tools (Optional[List[Dict[str, Any]]]): The schema of the tools to+ use for the request.++ Returns:+ Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `Stream[ChatCompletionChunk]` in the stream mode.+ """+ request_config = self._prepare_request(+ messages, response_format, tools+ )++ response = self._client.chat.completions.create(+ 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]]:+ r"""Runs inference of OpenRouter chat completion asynchronously.++ 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.+ """+ 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 response++ def check_model_config(self):+ r"""Check whether the model configuration contains any unexpected+ arguments to OpenRouter API. But OpenRouter API does not have any+ additional arguments to check.++ Raises:+ ValueError: If the model configuration dictionary contains any+ unexpected arguments to OpenRouter API.+ """+ for param in self.model_config_dict:+ if param not in OPENROUTER_API_PARAMS:+ raise ValueError(+ f"Unexpected argument `{param}` is "+ "input into OpenRouter model backend."+ )++ @property+ def stream(self) -> bool:+ r"""Returns whether the model is in stream mode, which sends partial+ results each time.++ Returns:+ bool: Whether the model is in stream mode.+ """+ return self.model_config_dict.get("stream", False)diff --git a/camel/types/enums.py b/camel/types/enums.pyindex 6602eb9ae..fa3da99b7 100644--- a/camel/types/enums.py+++ b/camel/types/enums.py@@ -63,6 +63,11 @@ class ModelType(UnifiedModelType, Enum):GROQ_MIXTRAL_8_7B = "mixtral-8x7b-32768"GROQ_GEMMA_2_9B_IT = "gemma2-9b-it"+ # OpenRouter models+ OPENROUTER_LLAMA_3_1_405B = "meta-llama/llama-3.3-405b-instruct"+ OPENROUTER_LLAMA_3_1_70B = "meta-llama/llama-3.3-70b-instruct"+ OPENROUTER_OLYMPICODER_7B = "open-r1/olympiccoder-7b:free"+# TogetherAI platform models support tool callingTOGETHER_LLAMA_3_1_8B = "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"TOGETHER_LLAMA_3_1_70B = "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"@@ -253,6 +258,7 @@ class ModelType(UnifiedModelType, Enum):self.is_together,self.is_sambanova,self.is_groq,+ self.is_openrouter,self.is_sglang,self.is_moonshot,self.is_siliconflow,@@ -342,6 +348,15 @@ class ModelType(UnifiedModelType, Enum):ModelType.GROQ_GEMMA_2_9B_IT,}+ @property+ def is_openrouter(self) -> bool:+ r"""Returns whether this type of models is served by OpenRouter."""+ return self in {+ ModelType.OPENROUTER_LLAMA_3_1_405B,+ ModelType.OPENROUTER_LLAMA_3_1_70B,+ ModelType.OPENROUTER_OLYMPICODER_7B,+ }+@propertydef is_together(self) -> bool:r"""Returns whether this type of models is served by Together AI."""@@ -580,6 +595,7 @@ class ModelType(UnifiedModelType, Enum):ModelType.MOONSHOT_V1_8K,ModelType.GLM_4V_FLASH,ModelType.GLM_4_AIRX,+ ModelType.OPENROUTER_OLYMPICODER_7B,}:return 8_192elif self in {@@ -686,6 +702,8 @@ class ModelType(UnifiedModelType, Enum):ModelType.SGLANG_QWEN_2_5_7B,ModelType.SGLANG_QWEN_2_5_32B,ModelType.SGLANG_QWEN_2_5_72B,+ ModelType.OPENROUTER_LLAMA_3_1_70B,+ ModelType.OPENROUTER_LLAMA_3_1_405B,}:return 131_072elif self in {@@ -881,6 +899,7 @@ class ModelPlatformType(Enum):AZURE = "azure"ANTHROPIC = "anthropic"GROQ = "groq"+ OPENROUTER = "openrouter"OLLAMA = "ollama"LITELLM = "litellm"ZHIPU = "zhipuai"@@ -931,6 +950,11 @@ class ModelPlatformType(Enum):r"""Returns whether this platform is groq."""return self is ModelPlatformType.GROQ+ @property+ def is_openrouter(self) -> bool:+ r"""Returns whether this platform is openrouter."""+ return self is ModelPlatformType.OPENROUTER+@propertydef is_ollama(self) -> bool:r"""Returns whether this platform is ollama."""diff --git a/camel/types/unified_model_type.py b/camel/types/unified_model_type.pyindex 45bba6ecf..d7148b025 100644--- a/camel/types/unified_model_type.py+++ b/camel/types/unified_model_type.py@@ -78,6 +78,11 @@ class UnifiedModelType(str):r"""Returns whether the model is a Groq served model."""return True+ @property+ def is_openrouter(self) -> bool:+ r"""Returns whether the model is a OpenRouter served model."""+ return True+@propertydef is_zhipuai(self) -> bool:r"""Returns whether the model is a Zhipuai model."""diff --git a/docs/key_modules/models.md b/docs/key_modules/models.mdindex 1a3fa2b1c..c09cf0bdf 100644--- a/docs/key_modules/models.md+++ b/docs/key_modules/models.md@@ -29,6 +29,7 @@ CAMEL supports a wide range of models, including [OpenAI’s GPT series](https:/| **TOGETHER AI** | [supported models](https://docs.together.ai/docs/chat-models) || **SambaNova** | [supported models](https://docs.sambanova.ai/cloud/docs/get-started/supported-models) || **Ollama** | [supported models](https://ollama.com/library) |+| **OpenRouter** | [supported models](https://openrouter.ai/models) || **LiteLLM** | [supported models](https://docs.litellm.ai/docs/providers) || **vLLM** | [supported models](https://docs.vllm.ai/en/latest/models/supported_models.html) || **SGLANG** | [supported models](https://sgl-project.github.io/references/supported_models.html) |diff --git a/examples/models/openrouter_model_example.py b/examples/models/openrouter_model_example.pynew file mode 100644index 000000000..97d600644--- /dev/null+++ b/examples/models/openrouter_model_example.py@@ -0,0 +1,48 @@+# ========= 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 camel.agents import ChatAgent+from camel.configs import OpenRouterConfig+from camel.models import ModelFactory+from camel.types import ModelPlatformType, ModelType++model = ModelFactory.create(+ model_platform=ModelPlatformType.OPENROUTER,+ model_type=ModelType.OPENROUTER_LLAMA_3_1_70B,+ model_config_dict=OpenRouterConfig(temperature=0.2).as_dict(),+)++# Define system message+sys_msg = "You are a helpful assistant."++# Set agent+camel_agent = ChatAgent(system_message=sys_msg, model=model)++user_msg = """Say hi to CAMEL AI, one open-source community+ dedicated to the study of autonomous and communicative agents."""++# Get response information+response = camel_agent.step(user_msg)+print(response.msgs[0].content)++'''+===============================================================================+Hello to the CAMEL AI community. It's great to see a group of like-minded+individuals coming together to explore and advance the field of autonomous and+communicative agents. Your open-source approach is truly commendable, as it+fosters collaboration, innovation, and transparency. I'm excited to learn more+about your projects and initiatives, and I'm happy to help in any way I can.+Keep pushing the boundaries of AI research and development!+===============================================================================+'''diff --git a/test/models/test_openrouter_model.py b/test/models/test_openrouter_model.pynew file mode 100644index 000000000..f2eb219b1--- /dev/null+++ b/test/models/test_openrouter_model.py@@ -0,0 +1,62 @@+# ========= 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 re++import pytest++from camel.configs import OpenRouterConfig+from camel.models import OpenRouterModel+from camel.types import ModelType+from camel.utils import OpenAITokenCounter++[email protected]_backend+ "model_type",+ [+ ModelType.OPENROUTER_LLAMA_3_1_405B,+ ModelType.OPENROUTER_LLAMA_3_1_70B,+ ModelType.OPENROUTER_OLYMPICODER_7B,+ ],+)+def test_openrouter_model(model_type: ModelType):+ model = OpenRouterModel(model_type)+ assert model.model_type == model_type+ assert model.model_config_dict == OpenRouterConfig().as_dict()+ assert isinstance(model.token_counter, OpenAITokenCounter)+ assert isinstance(model.model_type.value_for_tiktoken, str)+ assert isinstance(model.model_type.token_limit, int)++[email protected]_backend+def test_openrouter_model_unexpected_argument():+ model_type = ModelType.OPENROUTER_LLAMA_3_1_70B+ model_config_dict = {"model_path": "openrouter_llama_3_1_70B"}++ with pytest.raises(+ ValueError,+ match=re.escape(+ (+ "Unexpected argument `model_path` is "+ "input into OpenRouter model backend."+ )+ ),+ ):+ _ = OpenRouterModel(model_type, model_config_dict)++[email protected]_backend+def test_openrouter_model_stream_property():+ model = OpenRouterModel(ModelType.OPENROUTER_LLAMA_3_1_70B)+ assert model.stream is False