š« 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
Integrate Open-source Models (#245)
Wenxuan Li7f0315f91a68
diff --git a/README.md b/README.mdindex 65c7f071f..d4667fb2c 100644--- a/README.md+++ b/README.md@@ -151,6 +151,56 @@ python examples/ai_society/role_playing.pyPlease note that the environment variable is session-specific. If you open a new terminal window or tab, you will need to set the API key again in that new session.++## Use Open-Source Models as Backends++The basic workflow of using an open-sourced model as the backend is based on an external server running LLM inference service, e.g. during the development we chose [FastChat](https://github.com/lm-sys/FastChat) to run the service.++We do not fix the choice of server to decouple the implementation of any specific LLM inference server with CAMEL (indicating the server needs to be deployed by the user himself). But the server to be deployed must satisfy that **it supports OpenAI-compatible APIs, especially the method `openai.ChatCompletion.create`**.++Here are some instructions for enabling open-source backends, where we use the [FastChat](https://github.com/lm-sys/FastChat) and a LLaMA2-based model ([`meta-llama/Llama-2-7b-chat-hf`](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf)) in the example. Please install FastChat in advance following their installation guidance.++1. Before running CAMEL, we should firstly launch FastChat server following the guidance on https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md. The instructions summarized below should be kept running **in separate processes**:++```sh+# Launch the controller+python -m fastchat.serve.controller++# Launch the model worker(s)+python3 -m fastchat.serve.model_worker --model-path meta-llama/Llama-2-7b-chat-hf++# Launch the RESTful API server+python3 -m fastchat.serve.openai_api_server --host localhost --port 8000+```++2. After observing the controller successfully receiving the heart beat signal from the worker, the server should be ready for use at http://localhost:8000/v1.++3. Then we can try on running `role_playing_with_open_source_model.py`, where each agent in this example is initialized with specifying the `model_path` and `server_url`, similar to the example code below:++```python+system_message = # ...++agent_kwargs = dict(+ model=model_type,+ model_config=OpenSourceConfig(+ model_path="meta-llama/Llama-2-7b-chat-hf",+ server_url="http://localhost:8000/v1",+ ),+)++agent = ChatAgent(+ system_message,+ **agent_kwargs,+)+```++### Supported Models++- LLaMA2-based models+ - example: [meta-llama/Llama-2-7b-chat-hf](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf)+- Vicuna-based models+ - example: [lmsys/vicuna-7b-v1.5](https://huggingface.co/lmsys/vicuna-7b-v1.5)+## Data (Hosted on Hugging Face)| Dataset | Chat format | Instruction format | Chat format (translated) || -- | -- | -- | -- |diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.pyindex 7b0226eff..5cddd64c4 100644--- a/camel/agents/chat_agent.py+++ b/camel/agents/chat_agent.py@@ -27,11 +27,7 @@ from camel.functions import OpenAIFunctionfrom camel.messages import BaseMessage, FunctionCallingMessage, OpenAIMessagefrom camel.models import BaseModelBackend, ModelFactoryfrom camel.typing import ModelType, RoleType-from camel.utils import (- get_model_encoding,- num_tokens_from_messages,- openai_api_key_required,-)+from camel.utils import get_model_encoding, openai_api_key_required@dataclass(frozen=True)@@ -372,7 +368,8 @@ class ChatAgent(BaseAgent):openai_messages: List[OpenAIMessage]openai_messages = [record.to_openai_message() for record in messages]- num_tokens = num_tokens_from_messages(openai_messages, self.model)+ num_tokens = self.model_backend.count_tokens_from_messages(+ openai_messages)return openai_messages, num_tokensdiff --git a/camel/agents/critic_agent.py b/camel/agents/critic_agent.pyindex 2c928e2a7..ce18b8ee8 100644--- a/camel/agents/critic_agent.py+++ b/camel/agents/critic_agent.py@@ -53,8 +53,9 @@ class CriticAgent(ChatAgent):verbose: bool = False,logger_color: Any = Fore.MAGENTA,) -> None:- super().__init__(system_message, model, model_config,- message_window_size)+ super().__init__(system_message, model=model,+ model_config=model_config,+ message_window_size=message_window_size)self.options_dict: Dict[str, str] = dict()self.retry_attempts = retry_attemptsself.verbose = verbosediff --git a/camel/agents/task_agent.py b/camel/agents/task_agent.pyindex 4ffec3c04..06270d8e7 100644--- a/camel/agents/task_agent.py+++ b/camel/agents/task_agent.py@@ -74,7 +74,8 @@ class TaskSpecifyAgent(ChatAgent):content="You can make a task more specific.",)- super().__init__(system_message, model, model_config,+ super().__init__(system_message, model=model,+ model_config=model_config,output_language=output_language)def run(diff --git a/camel/configs.py b/camel/configs.pyindex ec9d455e7..0f24e2a09 100644--- a/camel/configs.py+++ b/camel/configs.py@@ -12,7 +12,7 @@# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========from abc import ABC-from dataclasses import dataclass, field+from dataclasses import asdict, dataclass, fieldfrom typing import Any, Dict, List, Optional, Sequence, Unionfrom camel.functions import OpenAIFunction@@ -132,3 +132,28 @@ class FunctionCallingConfig(ChatGPTConfig):function_call=function_call,**(kwargs or {}),)+++@dataclass(frozen=True)+class OpenSourceConfig(BaseConfig):+ r"""Defines parameters for setting up open-source models and includes+ parameters to be passed to chat completion function of OpenAI API.++ Args:+ model_path (str): The path to a local folder containing the model+ files or the model card in HuggingFace hub.+ server_url (str): The URL to the server running the model inference+ which will be used as the API base of OpenAI API.+ api_params (ChatGPTConfig): An instance of :obj:ChatGPTConfig to+ contain the arguments to be passed to OpenAI API.+ """+ model_path: str+ server_url: str+ api_params: ChatGPTConfig = ChatGPTConfig()+++OPENAI_API_PARAMS = {param for param in asdict(ChatGPTConfig()).keys()}+OPENAI_API_PARAMS_WITH_FUNCTIONS = {+ param+ for param in asdict(FunctionCallingConfig()).keys()+}diff --git a/camel/messages/base.py b/camel/messages/base.pyindex 061c86bee..26b3b1860 100644--- a/camel/messages/base.py+++ b/camel/messages/base.py@@ -21,7 +21,7 @@ from camel.messages import (OpenAIUserMessage,)from camel.prompts import CodePrompt, TextPrompt-from camel.typing import ModelType, RoleType+from camel.typing import RoleType@dataclass@@ -125,23 +125,6 @@ class BaseMessage:"""return item in self.content- def token_len(self, role_at_backend: str,- model: ModelType = ModelType.GPT_3_5_TURBO) -> int:- r"""Calculate the token length of the message for the specified model.-- Args:- role_at_backend (str): interpret this message as of a specified- role, so that the special tokens can be counted properly.- model (ModelType, optional): The model type to calculate the token- length. (default: :obj:`ModelType.GPT_3_5_TURBO`)-- Returns:- int: The token length of the message.- """- from camel.utils import num_tokens_from_messages- return num_tokens_from_messages(- [self.to_openai_message(role_at_backend)], model)-def extract_text_and_code_prompts(self) -> Tuple[List[TextPrompt], List[CodePrompt]]:r"""Extract text and code prompts from the message content.diff --git a/camel/models/__init__.py b/camel/models/__init__.pyindex da0ad1a6f..f12ea34c4 100644--- a/camel/models/__init__.py+++ b/camel/models/__init__.py@@ -14,11 +14,13 @@from .base_model import BaseModelBackendfrom .openai_model import OpenAIModelfrom .stub_model import StubModel+from .open_source_model import OpenSourceModelfrom .model_factory import ModelFactory__all__ = ['BaseModelBackend','OpenAIModel','StubModel',+ 'OpenSourceModel','ModelFactory',]diff --git a/camel/models/base_model.py b/camel/models/base_model.pyindex 8d058d24c..8f21c021d 100644--- a/camel/models/base_model.py+++ b/camel/models/base_model.py@@ -15,11 +15,13 @@ from abc import ABC, abstractmethodfrom typing import Any, Dict, Listfrom camel.typing import ModelType+from camel.utils import BaseTokenCounterclass BaseModelBackend(ABC):r"""Base class for different model backends.- May be OpenAI API, a local LLM, a stub for unit tests, etc."""+ May be OpenAI API, a local LLM, a stub for unit tests, etc.+ """def __init__(self, model_type: ModelType,model_config_dict: Dict[str, Any]) -> None:@@ -30,25 +32,62 @@ class BaseModelBackend(ABC):model_config_dict (Dict[str, Any]): A config dictionary."""self.model_type = model_type+self.model_config_dict = model_config_dict+ self.check_model_config()++ @property+ @abstractmethod+ 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.+ """+ pass@abstractmethoddef run(self, messages: List[Dict]) -> Dict[str, Any]:r"""Runs the query to the backend model.Args:- messages (List[Dict]): message list with the chat history+ messages (List[Dict]): Message list with the chat historyin OpenAI API format.Raises:- RuntimeError: if the return value from OpenAI API- is not a dict that is expected.+ RuntimeError: If the return value from OpenAI API+ is not a dict that is expected.Returns:Dict[str, Any]: All backends must return a dict in OpenAI format."""pass+ @abstractmethod+ def check_model_config(self):+ r"""Check whether the input model configuration contains unexpected+ arguments++ Raises:+ ValueError: If the model configuration dictionary contains any+ unexpected argument for this model class.+ """+ pass++ def count_tokens_from_messages(self, messages: List[Dict]) -> int:+ r"""Count the number of tokens in the messages using the specific+ tokenizer.++ Args:+ messages (List[Dict]): message list with the chat history+ in OpenAI API format.++ Returns:+ int: Number of tokens in the messages.+ """+ return self.token_counter.count_tokens_from_messages(messages)+@propertydef token_limit(self) -> int:r"""Returns the maximum token limit for a given model.diff --git a/camel/models/model_factory.py b/camel/models/model_factory.pyindex 6e4c4599c..b5b430f43 100644--- a/camel/models/model_factory.py+++ b/camel/models/model_factory.py@@ -13,7 +13,12 @@# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========from typing import Any, Dict-from camel.models import BaseModelBackend, OpenAIModel, StubModel+from camel.models import (+ BaseModelBackend,+ OpenAIModel,+ OpenSourceModel,+ StubModel,+)from camel.typing import ModelType@@ -31,7 +36,7 @@ class ModelFactory:Args:model_type (ModelType): Model for which a backend is created.- model_config_dict (Dict): a dictionary that will be fed into+ model_config_dict (Dict): A dictionary that will be fed intothe backend constructor.Raises:@@ -41,17 +46,14 @@ class ModelFactory:BaseModelBackend: The initialized backend."""model_class: Any- if model_type in {- ModelType.GPT_3_5_TURBO,- ModelType.GPT_3_5_TURBO_16K,- ModelType.GPT_4,- ModelType.GPT_4_32k,- }:+ if model_type.is_openai:model_class = OpenAIModelelif model_type == ModelType.STUB:model_class = StubModel+ elif model_type.is_open_source:+ model_class = OpenSourceModelelse:- raise ValueError("Unknown model")+ raise ValueError(f"Unknown model type `{model_type}` is input")inst = model_class(model_type, model_config_dict)return instdiff --git a/camel/models/open_source_model.py b/camel/models/open_source_model.pynew file mode 100644index 000000000..cea4f0c99--- /dev/null+++ b/camel/models/open_source_model.py@@ -0,0 +1,143 @@+# =========== 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 types import GeneratorType+from typing import Any, Dict, List, Optional++from camel.configs import OPENAI_API_PARAMS+from camel.messages import OpenAIMessage+from camel.models import BaseModelBackend+from camel.typing import ModelType+from camel.utils import BaseTokenCounter, OpenSourceTokenCounter+++class OpenSourceModel(BaseModelBackend):+ r"""Class for interace with OpenAI-API-compatible servers running+ open-source models.+ """++ def __init__(+ self,+ model_type: ModelType,+ model_config_dict: Dict[str, Any],+ ) -> None:+ r"""Constructor for model backends of Open-source models.++ Args:+ model_type (ModelType): Model for which a backend is created.+ model_config_dict (Dict[str, Any]): A dictionary that will+ be fed into :obj:`openai.ChatCompletion.create()`.+ """+ super().__init__(model_type, model_config_dict)+ self._token_counter: Optional[BaseTokenCounter] = None++ # Check whether the input model type is open-source+ if not model_type.is_open_source:+ raise ValueError(+ f"Model `{model_type}` is not a supported open-source model.")++ # Check whether input model path is empty+ model_path: Optional[str] = (self.model_config_dict.get(+ "model_path", None))+ if not model_path:+ raise ValueError("Path to open-source model is not provided.")+ self.model_path: str = model_path++ # Check whether the model name matches the model type+ self.model_name: str = self.model_path.split('/')[-1]+ if not self.model_type.validate_model_name(self.model_name):+ raise ValueError(+ f"Model name `{self.model_name}` does not match model type "+ f"`{self.model_type.value}`.")++ # Load the server URL and check whether it is None+ server_url: Optional[str] = (self.model_config_dict.get(+ "server_url", None))+ if not server_url:+ raise ValueError(+ "URL to server running open-source LLM is not provided.")+ self.server_url: str = server_url++ # Replace `model_config_dict` with only the params to be+ # passed to OpenAI API+ self.model_config_dict = self.model_config_dict["api_params"].__dict__++ @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 = OpenSourceTokenCounter(+ self.model_type, self.model_path)+ return self._token_counter++ def run(+ self,+ messages: List[Dict],+ ) -> Dict[str, Any]:+ r"""Run inference of OpenAI chat completion.++ Args:+ messages (List[Dict]): Message list with the chat history+ in OpenAI API format.++ Returns:+ Dict[str, Any]: Response in the OpenAI API format.+ """+ import openai+ openai.api_base = self.server_url++ messages_openai: List[OpenAIMessage] = messages+ response = openai.ChatCompletion.create(messages=messages_openai,+ model=self.model_name,+ **self.model_config_dict)+ if not self.stream:+ if not isinstance(response, Dict):+ raise RuntimeError("Unexpected batch return from OpenAI API")+ else:+ if not isinstance(response, GeneratorType):+ raise RuntimeError("Unexpected stream return from OpenAI API")+ return response++ def check_model_config(self):+ r"""Check whether the model configuration is valid for open-source+ model backends.++ 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`.+ """+ if ("model_path" not in self.model_config_dict+ or "server_url" not in self.model_config_dict):+ raise ValueError(+ "Invalid configuration for open-source model backend with "+ ":obj:`model_path` or :obj:`server_url` missing.")++ for param in self.model_config_dict["api_params"].__dict__:+ if param not in OPENAI_API_PARAMS:+ raise ValueError(f"Unexpected argument `{param}` is "+ "input into open-source 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/models/openai_model.py b/camel/models/openai_model.pyindex b0a0fe78f..d0ba75c69 100644--- a/camel/models/openai_model.py+++ b/camel/models/openai_model.py@@ -12,11 +12,15 @@# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========from types import GeneratorType-from typing import Any, Dict, List+from typing import Any, Dict, List, Optional+from camel.configs import OPENAI_API_PARAMS_WITH_FUNCTIONSfrom camel.messages import OpenAIMessagefrom camel.models import BaseModelBackendfrom camel.typing import ModelType+from camel.utils import BaseTokenCounter, OpenAITokenCounter++DEFAULT_API_BASE = "https://api.openai.com/v1"class OpenAIModel(BaseModelBackend):@@ -33,6 +37,19 @@ class OpenAIModel(BaseModelBackend):be fed into openai.ChatCompletion.create()."""super().__init__(model_type, model_config_dict)+ self._token_counter: Optional[BaseTokenCounter] = None++ @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(self.model_type)+ return self._token_counterdef run(self,@@ -48,6 +65,8 @@ class OpenAIModel(BaseModelBackend):Dict[str, Any]: Response in the OpenAI API format."""import openai+ openai.api_base = DEFAULT_API_BASE+messages_openai: List[OpenAIMessage] = messagesresponse = openai.ChatCompletion.create(messages=messages_openai,model=self.model_type.value,@@ -60,6 +79,19 @@ class OpenAIModel(BaseModelBackend):raise RuntimeError("Unexpected stream return from OpenAI API")return response+ def check_model_config(self):+ r"""Check whether the model configuration contains any+ unexpected arguments to OpenAI API.++ Raises:+ ValueError: If the model configuration dictionary contains any+ unexpected arguments to OpenAI API.+ """+ for param in self.model_config_dict:+ if param not in OPENAI_API_PARAMS_WITH_FUNCTIONS:+ raise ValueError(f"Unexpected argument `{param}` is "+ "input into OpenAI model backend.")+@propertydef stream(self) -> bool:r"""Returns whether the model is in stream mode,diff --git a/camel/models/stub_model.py b/camel/models/stub_model.pyindex ee6d7d951..ffc361570 100644--- a/camel/models/stub_model.py+++ b/camel/models/stub_model.py@@ -11,10 +11,28 @@# See the License for the specific language governing permissions and# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========-from typing import Any, Dict, List+from typing import Any, Dict, List, Optional+from camel.messages import OpenAIMessagefrom camel.models import BaseModelBackendfrom camel.typing import ModelType+from camel.utils import BaseTokenCounter+++class StubTokenCounter(BaseTokenCounter):++ def count_tokens_from_messages(self, messages: List[OpenAIMessage]) -> int:+ r"""Token counting for STUB models, directly returning a constant.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ int: A constant to act as the number of the tokens in the+ messages.+ """+ return 10class StubModel(BaseModelBackend):@@ -25,7 +43,19 @@ class StubModel(BaseModelBackend):model_config_dict: Dict[str, Any]) -> None:r"""All arguments are unused for the dummy model."""super().__init__(model_type, model_config_dict)- pass+ self._token_counter: Optional[BaseTokenCounter] = None++ @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 = StubTokenCounter()+ return self._token_counterdef run(self, messages: List[Dict]) -> Dict[str, Any]:r"""Run fake inference by returning a fixed string.@@ -44,3 +74,8 @@ class StubModel(BaseModelBackend):message=dict(content=ARBITRARY_STRING, role="assistant"))],)++ def check_model_config(self):+ r"""Directly pass the check on arguments to STUB model.+ """+ passdiff --git a/camel/typing.py b/camel/typing.pyindex 1b274d02e..a5bc0fba6 100644--- a/camel/typing.py+++ b/camel/typing.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 refrom enum import Enum@@ -29,10 +30,43 @@ class ModelType(Enum):GPT_4_32k = "gpt-4-32k"STUB = "stub"+ LLAMA_2 = "llama-2"+ VICUNA = "vicuna"+ VICUNA_16K = "vicuna-16k"+@propertydef value_for_tiktoken(self) -> str:return self.value if self.name != "STUB" else "gpt-3.5-turbo"+ @property+ def is_openai(self) -> bool:+ r"""Returns whether this type of models is an OpenAI-released model.++ Returns:+ bool: Whether this type of models belongs to OpenAI.+ """+ if self.name in {+ "GPT_3_5_TURBO",+ "GPT_3_5_TURBO_16K",+ "GPT_4",+ "GPT_4_32k",+ }:+ return True+ else:+ return False++ @property+ def is_open_source(self) -> bool:+ r"""Returns whether this type of models is open-source.++ Returns:+ bool: Whether this type of models is open-source.+ """+ if self.name in {"LLAMA_2", "VICUNA", "VICUNA_16K"}:+ return True+ else:+ return False+@propertydef token_limit(self) -> int:r"""Returns the maximum token limit for a given model.@@ -49,9 +83,36 @@ class ModelType(Enum):return 32768elif self is ModelType.STUB:return 4096+ elif self is ModelType.LLAMA_2:+ return 4096+ elif self is ModelType.VICUNA:+ # reference: https://lmsys.org/blog/2023-03-30-vicuna/+ return 2048+ elif self is ModelType.VICUNA_16K:+ return 16384else:raise ValueError("Unknown model type")+ def validate_model_name(self, model_name: str) -> bool:+ r"""Checks whether the model type and the model name matches.++ Args:+ model_name (str): The name of the model, e.g. "vicuna-7b-v1.5".+ Returns:+ bool: Whether the model type mathches the model name.+ """+ if self is ModelType.VICUNA:+ pattern = r'^vicuna-\d+b-v\d+\.\d+$'+ return bool(re.match(pattern, model_name))+ elif self is ModelType.VICUNA_16K:+ pattern = r'^vicuna-\d+b-v\d+\.\d+-16k$'+ return bool(re.match(pattern, model_name))+ elif self is ModelType.LLAMA_2:+ return (self.value in model_name.lower()+ or "llama2" in model_name.lower())+ else:+ return self.value in model_name.lower()+class TaskType(Enum):AI_SOCIETY = "ai_society"diff --git a/camel/utils/__init__.py b/camel/utils/__init__.pyindex 693b7a818..2df33571f 100644--- a/camel/utils/__init__.py+++ b/camel/utils/__init__.py@@ -13,9 +13,6 @@# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========from .python_interpreter import PythonInterpreterfrom .functions import (- get_model_encoding,- count_tokens_openai_chat_models,- num_tokens_from_messages,openai_api_key_required,print_text_animated,get_prompt_template_key_words,@@ -24,11 +21,15 @@ from .functions import (parse_doc,get_task_list,)+from .token_counting import (+ get_model_encoding,+ BaseTokenCounter,+ OpenAITokenCounter,+ OpenSourceTokenCounter,+)__all__ = [- 'get_model_encoding','count_tokens_openai_chat_models',- 'num_tokens_from_messages','openai_api_key_required','print_text_animated','get_prompt_template_key_words',@@ -37,4 +38,8 @@ __all__ = ['PythonInterpreter','parse_doc','get_task_list',+ 'get_model_encoding',+ 'BaseTokenCounter',+ 'OpenAITokenCounter',+ 'OpenSourceTokenCounter',]diff --git a/camel/utils/functions.py b/camel/utils/functions.pyindex 3f211310d..2b778ed2e 100644--- a/camel/utils/functions.py+++ b/camel/utils/functions.py@@ -30,127 +30,12 @@ from typing import ()import requests-import tiktoken-from camel.messages import OpenAIMessagefrom camel.typing import ModelType, TaskTypeF = TypeVar('F', bound=Callable[..., Any])-def get_model_encoding(value_for_tiktoken: str):- r"""Get model encoding from tiktoken.-- Args:- value_for_tiktoken: Model value for tiktoken.-- Returns:- tiktoken.Encoding: Model encoding.- """- try:- encoding = tiktoken.encoding_for_model(value_for_tiktoken)- except KeyError:- print("Model not found. Using cl100k_base encoding.")- encoding = tiktoken.get_encoding("cl100k_base")- return encoding---def count_tokens_openai_chat_models(- messages: List[OpenAIMessage],- encoding: tiktoken.Encoding,- tokens_per_message: int,- tokens_per_name: int,-) -> int:- r"""Counts the number of tokens required to generate an OpenAI chat based- on a given list of messages.-- Args:- messages (List[OpenAIMessage]): The list of messages.- encoding (tiktoken.Encoding): The encoding method to use.- tokens_per_message (int): Number of tokens to be added- to each message.- tokens_per_name (int): Number of tokens to be added if- name existed in the message.-- Returns:- int: The number of tokens required.- """- num_tokens = 0- for message in messages:- num_tokens += tokens_per_message- for key, value in message.items():- num_tokens += len(encoding.encode(str(value)))- if key == "name":- num_tokens += tokens_per_name- num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>- return num_tokens---def num_tokens_from_messages(- messages: List[OpenAIMessage],- model: ModelType,-) -> int:- r"""Returns the number of tokens used by a list of messages.-- Args:- messages (List[OpenAIMessage]): The list of messages to count the- number of tokens for.- model (ModelType): The OpenAI model used to encode the messages.-- Returns:- int: The total number of tokens used by the messages.-- Raises:- NotImplementedError: If the specified `model` is not implemented.-- References:- - https://github.com/openai/openai-python/blob/main/chatml.md- - https://platform.openai.com/docs/models/gpt-4- - https://platform.openai.com/docs/models/gpt-3-5- """- return _num_tokens_from_messages(messages, model.value_for_tiktoken)---# flake8: noqa :E501-def _num_tokens_from_messages(messages: List[OpenAIMessage], model: str):- r"""Return the number of tokens used by a list of messages.-- References:- - https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb- """- if model in {- "gpt-3.5-turbo-0613",- "gpt-3.5-turbo-16k-0613",- "gpt-4-0314",- "gpt-4-32k-0314",- "gpt-4-0613",- "gpt-4-32k-0613",- }:- tokens_per_message = 3- tokens_per_name = 1- elif model == "gpt-3.5-turbo-0301":- # Every message follows <|start|>{role/name}\n{content}<|end|>\n- tokens_per_message = 4- # If there's a name, the role is omitted- tokens_per_name = -1- elif "gpt-3.5-turbo" in model:- return _num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")- elif "gpt-4" in model:- return _num_tokens_from_messages(messages, model="gpt-4-0613")- else:- raise NotImplementedError(- f"`num_tokens_from_messages`` is not presently implemented "- f"for model {model}. "- f"See https://github.com/openai/openai-python/blob/main/chatml.md "- f"for information on how messages are converted to tokens. "- f"See https://platform.openai.com/docs/models/gpt-4"- f"or https://platform.openai.com/docs/models/gpt-3-5"- f"for information about openai chat models.")- encoding = get_model_encoding(model)- return count_tokens_openai_chat_models(messages, encoding,- tokens_per_message, tokens_per_name)--def openai_api_key_required(func: F) -> F:r"""Decorator that checks if the OpenAI API key is available in theenvironment variables.@@ -173,6 +58,8 @@ def openai_api_key_required(func: F) -> F:raise ValueError("Expected ChatAgent")if self.model == ModelType.STUB:return func(self, *args, **kwargs)+ elif self.model.is_open_source:+ return func(self, *args, **kwargs)elif 'OPENAI_API_KEY' in os.environ:return func(self, *args, **kwargs)else:@@ -271,7 +158,7 @@ def parse_doc(func: Callable) -> Dict[str, Any]:properties = {}required = []- parts = re.split('\n\s*\n', doc)+ parts = re.split(r'\n\s*\n', doc)func_desc = parts[0].strip()args_section = next((p for p in parts if 'Args:' in p), None)diff --git a/camel/utils/token_counting.py b/camel/utils/token_counting.pynew file mode 100644index 000000000..b6325da83--- /dev/null+++ b/camel/utils/token_counting.py@@ -0,0 +1,214 @@+# =========== 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 abc import ABC, abstractmethod+from typing import Any, Dict, List++from camel.messages import OpenAIMessage+from camel.typing import ModelType+++def messages_to_prompt(messages: List[OpenAIMessage], model: ModelType) -> str:+ r"""Parse the message list into a single prompt following model-specifc+ formats.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.+ model (ModelType): Model type for which messages will be parsed.++ Returns:+ str: A single prompt summarizing all the messages.+ """+ system_message = messages[0]["content"]++ ret: str+ if model == ModelType.LLAMA_2:+ # reference: https://github.com/facebookresearch/llama/blob/cfc3fc8c1968d390eb830e65c63865e980873a06/llama/generation.py#L212+ seps = [" ", " </s><s>"]+ role_map = {"user": "[INST]", "assistant": "[/INST]"}++ system_prompt = f"[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n"+ ret = ""+ for i, msg in enumerate(messages[1:]):+ role = role_map[msg["role"]]+ message = msg["content"]+ if message:+ if i == 0:+ ret += system_prompt + message+ else:+ ret += role + " " + message + seps[i % 2]+ else:+ ret += role+ return ret+ elif model == ModelType.VICUNA or model == ModelType.VICUNA_16K:+ seps = [" ", "</s>"]+ role_map = {"user": "USER", "assistant": "ASSISTANT"}++ system_prompt = f"{system_message}"+ ret = system_prompt + seps[0]+ for i, msg in enumerate(messages[1:]):+ role = role_map[msg["role"]]+ message = msg["content"]+ if message:+ ret += role + ": " + message + seps[i % 2]+ else:+ ret += role + ":"+ return ret+ else:+ raise ValueError(f"Invalid model type: {model}")+++def get_model_encoding(value_for_tiktoken: str):+ r"""Get model encoding from tiktoken.++ Args:+ value_for_tiktoken: Model value for tiktoken.++ Returns:+ tiktoken.Encoding: Model encoding.+ """+ import tiktoken+ try:+ encoding = tiktoken.encoding_for_model(value_for_tiktoken)+ except KeyError:+ print("Model not found. Using cl100k_base encoding.")+ encoding = tiktoken.get_encoding("cl100k_base")+ return encoding+++class BaseTokenCounter(ABC):+ r"""Base class for token counters of different kinds of models."""++ @abstractmethod+ def count_tokens_from_messages(self, messages: List[OpenAIMessage]) -> int:+ r"""Count number of tokens in the provided message list.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ int: Number of tokens in the messages.+ """+ pass+++class OpenSourceTokenCounter(BaseTokenCounter):++ def __init__(self, model_type: ModelType, model_path: str):+ r"""Constructor for the token counter for open-source models.++ Args:+ model_type (ModelType): Model type for which tokens will be+ counted.+ model_path (str): The path to the model files, where the tokenizer+ model should be located.+ """++ # Use a fast Rust-based tokenizer if it is supported for a given model.+ # If a fast tokenizer is not available for a given model,+ # a normal Python-based tokenizer is returned instead.+ from transformers import AutoTokenizer+ try:+ tokenizer = AutoTokenizer.from_pretrained(+ model_path,+ use_fast=True,+ )+ except TypeError:+ tokenizer = AutoTokenizer.from_pretrained(+ model_path,+ use_fast=False,+ )+ except:+ raise ValueError(+ f"Invalid `model_path` ({model_path}) is provided. "+ "Tokenizer loading failed.")++ self.tokenizer = tokenizer+ self.model_type = model_type++ def count_tokens_from_messages(self, messages: List[OpenAIMessage]) -> int:+ r"""Count number of tokens in the provided message list using+ loaded tokenizer specific for this type of model.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ int: Number of tokens in the messages.+ """+ prompt = messages_to_prompt(messages, self.model_type)+ input_ids = self.tokenizer(prompt).input_ids++ return len(input_ids)+++class OpenAITokenCounter(BaseTokenCounter):++ def __init__(self, model: ModelType):+ r"""Constructor for the token counter for OpenAI models.++ Args:+ model_type (ModelType): Model type for which tokens will be+ counted.+ """+ self.model: str = model.value_for_tiktoken++ self.tokens_per_message: int+ self.tokens_per_name: int++ if self.model == "gpt-3.5-turbo-0301":+ # Every message follows <|start|>{role/name}\n{content}<|end|>\n+ self.tokens_per_message = 4+ # If there's a name, the role is omitted+ self.tokens_per_name = -1+ elif ("gpt-3.5-turbo" in self.model) or ("gpt-4" in self.model):+ self.tokens_per_message = 3+ self.tokens_per_name = 1+ else:+ # flake8: noqa :E501+ raise NotImplementedError(+ "Token counting for OpenAI Models is not presently "+ f"implemented for model {model}. "+ "See https://github.com/openai/openai-python/blob/main/chatml.md "+ "for information on how messages are converted to tokens. "+ "See https://platform.openai.com/docs/models/gpt-4"+ "or https://platform.openai.com/docs/models/gpt-3-5"+ "for information about openai chat models.")++ self.encoding = get_model_encoding(self.model)++ def count_tokens_from_messages(self, messages: List[OpenAIMessage]) -> int:+ r"""Count number of tokens in the provided message list with the+ help of package tiktoken.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.++ Returns:+ int: Number of tokens in the messages.+ """+ num_tokens = 0+ for message in messages:+ num_tokens += self.tokens_per_message+ for key, value in message.items():+ num_tokens += len(self.encoding.encode(str(value)))+ if key == "name":+ num_tokens += self.tokens_per_name++ # every reply is primed with <|start|>assistant<|message|>+ num_tokens += 3+ return num_tokensdiff --git a/examples/open_source_models/role_playing_with_open_source_model.py b/examples/open_source_models/role_playing_with_open_source_model.pynew file mode 100644index 000000000..f7bd6a31c--- /dev/null+++ b/examples/open_source_models/role_playing_with_open_source_model.py@@ -0,0 +1,97 @@+# =========== 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 colorama import Fore++from camel.configs import ChatGPTConfig, OpenSourceConfig+from camel.societies import RolePlaying+from camel.typing import ModelType+from camel.utils import print_text_animated+++def main(model_type=None, model_path=" ", server_url=" ") -> None:+ task_prompt = "Develop a trading bot for the stock market"++ agent_kwargs = {+ role: dict(+ model=model_type,+ model_config=OpenSourceConfig(+ model_path=model_path,+ server_url=server_url,+ api_params=ChatGPTConfig(temperature=0),+ ),+ )+ for role in ["assistant", "user", "task-specify"]+ }++ role_play_session = RolePlaying(+ assistant_role_name="Python Programmer",+ assistant_agent_kwargs=agent_kwargs["assistant"],+ user_role_name="Stock Trader",+ user_agent_kwargs=agent_kwargs["user"],+ task_prompt=task_prompt,+ with_task_specify=True,+ task_specify_agent_kwargs=agent_kwargs["task-specify"],+ )++ print(+ Fore.GREEN ++ f"AI Assistant sys message:\n{role_play_session.assistant_sys_msg}\n")+ print(Fore.BLUE ++ f"AI User sys message:\n{role_play_session.user_sys_msg}\n")++ print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")+ print(+ Fore.CYAN ++ f"Specified task prompt:\n{role_play_session.specified_task_prompt}\n")+ print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")++ chat_turn_limit, n = 50, 0+ input_assistant_msg, _ = role_play_session.init_chat()+ while n < chat_turn_limit:+ n += 1+ assistant_response, user_response = role_play_session.step(+ input_assistant_msg)++ if assistant_response.terminated:+ print(Fore.GREEN ++ ("AI Assistant terminated. Reason: "+ f"{assistant_response.info['termination_reasons']}."))+ break+ if user_response.terminated:+ print(Fore.GREEN ++ ("AI User terminated. "+ f"Reason: {user_response.info['termination_reasons']}."))+ break++ print_text_animated(Fore.BLUE ++ f"AI User:\n\n{user_response.msg.content}\n")+ print_text_animated(Fore.GREEN + "AI Assistant:\n\n"+ f"{assistant_response.msg.content}\n")++ if "CAMEL_TASK_DONE" in user_response.msg.content:+ break++ input_assistant_msg = assistant_response.msg+++if __name__ == "__main__":+ # Here :obj:`model_type` can be any of the supported open-source+ # model types and :obj:`model_path` should be set corresponding to+ # model type. For example, to use Vicuna, we can set:+ # model_path = "lmsys/vicuna-7b-v1.5"+ main(+ model_type=ModelType.LLAMA_2,+ model_path="meta-llama/Llama-2-7b-chat-hf",+ server_url="http://localhost:8000/v1",+ )diff --git a/examples/test/test_ai_society_example.py b/examples/test/test_ai_society_example.pyindex 89410bcb2..07b252520 100644--- a/examples/test/test_ai_society_example.py+++ b/examples/test/test_ai_society_example.py@@ -15,6 +15,7 @@ from mock import patchimport examples.ai_society.role_playingimport examples.function_call.role_playing_with_function+import examples.open_source_models.role_playing_with_open_source_modelfrom camel.typing import ModelType@@ -26,3 +27,9 @@ def test_ai_society_role_playing_example():def test_role_playing_with_function_example():with patch('time.sleep', return_value=None):examples.function_call.role_playing_with_function.main(ModelType.STUB)+++def test_role_playing_with_open_source_model():+ with patch('time.sleep', return_value=None):+ examples.open_source_models.role_playing_with_open_source_model.main(+ ModelType.STUB)diff --git a/pyproject.toml b/pyproject.tomlindex 4d69c5d8f..0f47b62d3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -34,6 +34,7 @@ jsonschema = "^4"types-colorama = "^0"types-requests = "^2"bs4 = "^0"+protobuf = "^4"transformers = { version = "^4", optional = true }diffusers = { version = "^0", optional = true }diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.pyindex 2a84785d3..885a40a40 100644--- a/test/agents/test_chat_agent.py+++ b/test/agents/test_chat_agent.py@@ -22,7 +22,6 @@ from camel.functions import MATH_FUNCSfrom camel.generators import SystemMessageGeneratorfrom camel.messages import BaseMessagefrom camel.typing import ModelType, RoleType, TaskType-from camel.utils import num_tokens_from_messagesparametrize = pytest.mark.parametrize('model', [ModelType.STUB,@@ -56,21 +55,6 @@ def test_chat_agent(model: ModelType):assert isinstance(assistant_response.info, dict)assert assistant_response.info['id'] is not None- assistant.reset()- token_limit = assistant.model_token_limit- user_msg = BaseMessage(role_name="Patient", role_type=RoleType.USER,- meta_dict=dict(),- content="token" * (token_limit + 1))- assistant_response = assistant.step(user_msg)-- assert isinstance(assistant_response.msgs, list)- assert len(assistant_response.msgs) == 0- assert isinstance(assistant_response.terminated, bool)- assert assistant_response.terminated is True- assert isinstance(assistant_response.info, dict)- assert (assistant_response.info['termination_reasons'][0] ==- "max_tokens_exceeded")-@pytest.mark.model_backenddef test_chat_agent_stored_messages():@@ -134,10 +118,8 @@ def test_chat_agent_step_exceed_token_number():msgs = [system_msg, user_msg_record]expect_openai_messages = [record.to_openai_message() for record in msgs]- expect_num_tokens = num_tokens_from_messages(- expect_openai_messages,- assistant.model,- )+ expect_num_tokens = assistant.model_backend.count_tokens_from_messages(+ expect_openai_messages)response = assistant.step(user_msg)assert len(response.msgs) == 0diff --git a/test/agents/test_embodied_agent.py b/test/agents/test_embodied_agent.pyindex e90fa3c41..11239fb48 100644--- a/test/agents/test_embodied_agent.py+++ b/test/agents/test_embodied_agent.py@@ -14,6 +14,7 @@import binasciiimport pytest+import requestsfrom camel.agents import EmbodiedAgent, HuggingFaceToolAgentfrom camel.generators import SystemMessageGenerator@@ -51,7 +52,7 @@ def test_step():)try:response = embodied_agent.step(user_msg)- except binascii.Error as ex:+ except (binascii.Error, requests.exceptions.ConnectionError) as ex:print("Warning: caught an exception, ignoring it since "f"it is a known issue of Huggingface ({str(ex)})")returndiff --git a/test/agents/tool_agents/test_hugging_face_tool_agent.py b/test/agents/tool_agents/test_hugging_face_tool_agent.pyindex 942b113e5..f059d8599 100644--- a/test/agents/tool_agents/test_hugging_face_tool_agent.py+++ b/test/agents/tool_agents/test_hugging_face_tool_agent.py@@ -14,6 +14,7 @@import binasciiimport pytest+import requestsfrom camel.agents import HuggingFaceToolAgent@@ -34,7 +35,7 @@ def test_hugging_face_tool_agent_step():agent = HuggingFaceToolAgent("hugging_face_tool_agent")try:result = agent.step("Generate an image of a boat in the water")- except binascii.Error as ex:+ except (binascii.Error, requests.exceptions.ConnectionError) as ex:print("Warning: caught an exception, ignoring it since "f"it is a known issue of Huggingface ({str(ex)})")return@@ -48,7 +49,7 @@ def test_hugging_face_tool_agent_chat():agent = HuggingFaceToolAgent("hugging_face_tool_agent")try:result = agent.chat("Show me an image of a capybara")- except binascii.Error as ex:+ except (binascii.Error, requests.exceptions.ConnectionError) as ex:print("Warning: caught an exception, ignoring it since "f"it is a known issue of Huggingface ({str(ex)})")returndiff --git a/test/messages/test_message_base.py b/test/messages/test_message_base.pyindex d0bdf5f12..9d83d2b87 100644--- a/test/messages/test_message_base.py+++ b/test/messages/test_message_base.py@@ -47,12 +47,6 @@ def test_base_message_contains_operator(base_message: BaseMessage):assert "foo" not in base_message-def test_base_message_token_len(base_message: BaseMessage):- token_len = base_message.token_len("user")- assert isinstance(token_len, int)- assert token_len == 9--def test_extract_text_and_code_prompts():base_message = BaseMessage(role_name="test_role_name", role_type=RoleType.USER, meta_dict=dict(),diff --git a/test/models/test_open_source_model.py b/test/models/test_open_source_model.pynew file mode 100644index 000000000..7a804a231--- /dev/null+++ b/test/models/test_open_source_model.py@@ -0,0 +1,165 @@+# =========== 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. ===========+import re++import pytest++from camel.configs import (+ ChatGPTConfig,+ FunctionCallingConfig,+ OpenSourceConfig,+)+from camel.models import OpenSourceModel+from camel.typing import ModelType+from camel.utils import OpenSourceTokenCounter++MODEL_PATH_MAP = {+ ModelType.VICUNA: "lmsys/vicuna-7b-v1.5",+ ModelType.VICUNA_16K: "lmsys/vicuna-7b-v1.5-16k",+}++[email protected]_backend[email protected]("model_type", [+ ModelType.VICUNA,+ ModelType.VICUNA_16K,+])+def test_open_source_model(model_type):+ model_path = MODEL_PATH_MAP[model_type]+ model_name = model_path.split('/')[-1]+ model_config = OpenSourceConfig(+ model_path=model_path,+ server_url="http://localhost:8000/v1",+ )+ model_config_dict = model_config.__dict__+ model = OpenSourceModel(model_type, model_config_dict)++ assert model.model_type == model_type+ assert model.model_name == model_name+ assert model.server_url == model_config.server_url+ assert model.model_config_dict == model_config.api_params.__dict__++ assert isinstance(model.token_counter, OpenSourceTokenCounter)+ assert isinstance(model.model_type.value_for_tiktoken, str)+ assert isinstance(model.model_type.token_limit, int)++[email protected]_backend+def test_open_source_model_close_source_model_type():+ model_type = ModelType.GPT_3_5_TURBO+ model_path = MODEL_PATH_MAP[ModelType.VICUNA]+ model_config = OpenSourceConfig(+ model_path=model_path,+ server_url="http://localhost:8000/v1",+ )+ model_config_dict = model_config.__dict__++ with pytest.raises(+ ValueError, match=re.escape(+ ("Model `ModelType.GPT_3_5_TURBO` is not a supported"+ " open-source model."))):+ _ = OpenSourceModel(model_type, model_config_dict)++[email protected]_backend+def test_open_source_model_mismatched_model_config():+ model_type = ModelType.VICUNA+ model_config = ChatGPTConfig()+ model_config_dict = model_config.__dict__++ with pytest.raises(+ ValueError, match=re.escape(+ ("Invalid configuration for open-source model backend with "+ ":obj:`model_path` or :obj:`server_url` missing."))):+ _ = OpenSourceModel(model_type, model_config_dict)++[email protected]_backend+def test_open_source_model_unexpected_argument():+ model_type = ModelType.VICUNA+ model_path = MODEL_PATH_MAP[ModelType.VICUNA]+ model_config = OpenSourceConfig(+ model_path=model_path,+ server_url="http://localhost:8000/v1",+ api_params=FunctionCallingConfig(),+ )+ model_config_dict = model_config.__dict__++ with pytest.raises(+ ValueError, match=re.escape(+ ("Unexpected argument `functions` is "+ "input into open-source model backend."))):+ _ = OpenSourceModel(model_type, model_config_dict)++[email protected]_backend+def test_open_source_model_invalid_model_path():+ model_type = ModelType.VICUNA+ model_path = "vicuna-7b-v1.5"+ model_config = OpenSourceConfig(+ model_path=model_path,+ server_url="http://localhost:8000/v1",+ )+ model_config_dict = model_config.__dict__++ with pytest.raises(+ ValueError, match=re.escape(+ ("Invalid `model_path` (vicuna-7b-v1.5) is provided. "+ "Tokenizer loading failed."))):+ model = OpenSourceModel(model_type, model_config_dict)+ _ = model.token_counter++[email protected]_backend+def test_open_source_model_unmatched_model_path():+ model_type = ModelType.LLAMA_2+ model_path = MODEL_PATH_MAP[ModelType.VICUNA]+ model_config = OpenSourceConfig(+ model_path=model_path,+ server_url="http://localhost:8000/v1",+ )+ model_config_dict = model_config.__dict__++ with pytest.raises(+ ValueError,+ match=(f"Model name `vicuna-7b-v1.5` does not match model type "+ f"`{model_type.value}`.")):+ _ = OpenSourceModel(model_type, model_config_dict)++[email protected]_backend+def test_open_source_model_missing_model_path():+ model_type = ModelType.VICUNA+ model_config = OpenSourceConfig(+ model_path=None,+ server_url="http://localhost:8000/v1",+ )+ model_config_dict = model_config.__dict__++ with pytest.raises(ValueError,+ match=("Path to open-source model is not provided.")):+ _ = OpenSourceModel(model_type, model_config_dict)++[email protected]_backend+def test_open_source_model_missing_server_url():+ model_type = ModelType.VICUNA+ model_path = MODEL_PATH_MAP[ModelType.VICUNA]+ model_config = OpenSourceConfig(model_path=model_path, server_url=None)+ model_config_dict = model_config.__dict__++ with pytest.raises(+ ValueError,+ match=("URL to server running open-source LLM is not provided.")):+ _ = OpenSourceModel(model_type, model_config_dict)diff --git a/test/models/test_openai_model.py b/test/models/test_openai_model.pyindex d341ffb64..043754066 100644--- a/test/models/test_openai_model.py+++ b/test/models/test_openai_model.py@@ -11,11 +11,14 @@# See the License for the specific language governing permissions and# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========+import re+import pytest-from camel.configs import ChatGPTConfig+from camel.configs import ChatGPTConfig, OpenSourceConfigfrom camel.models import OpenAIModelfrom camel.typing import ModelType+from camel.utils import OpenAITokenCounter@pytest.mark.model_backend@@ -29,5 +32,21 @@ def test_openai_model(model_type):model = OpenAIModel(model_type, model_config_dict)assert model.model_type == model_typeassert model.model_config_dict == model_config_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_openai_model_unexpected_argument():+ model_type = ModelType.GPT_4+ model_config = OpenSourceConfig(+ model_path="vicuna-7b-v1.5",+ server_url="http://localhost:8000/v1",+ )+ model_config_dict = model_config.__dict__++ with pytest.raises(+ ValueError, match=re.escape(("Unexpected argument `model_path` is "+ "input into OpenAI model backend."))):+ _ = OpenAIModel(model_type, model_config_dict)