Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

refactor: `ChatAgent` model part (#574)

Wendong-Fanbfb9da068e2a
diff --git a/README.md b/README.md
index 3b4b63304..f87a68248 100644
--- a/README.md
+++ b/README.md
@@ -198,8 +198,9 @@ python3 -m fastchat.serve.openai_api_server --host localhost --port 8000
```python
system_message = # ...
-agent_kwargs = dict(
- model=model_type,
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENSOURCE
+ model_type=ModelType.LLAMA_2,
model_config=OpenSourceConfig(
model_path="meta-llama/Llama-2-7b-chat-hf",
server_url="http://localhost:8000/v1",
@@ -208,7 +209,7 @@ agent_kwargs = dict(
agent = ChatAgent(
system_message,
- **agent_kwargs,
+ model=model,
)
```
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index e54937ab5..db04856e4 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -32,6 +32,7 @@ from camel.responses import ChatAgentResponse
from camel.types import (
ChatCompletion,
ChatCompletionChunk,
+ ModelPlatformType,
ModelType,
OpenAIBackendRole,
RoleType,
@@ -41,7 +42,6 @@ from camel.utils import get_model_encoding
if TYPE_CHECKING:
from openai import Stream
- from camel.configs import BaseConfig
from camel.functions import OpenAIFunction
from camel.terminators import ResponseTerminator
@@ -80,10 +80,9 @@ class ChatAgent(BaseAgent):
Args:
system_message (BaseMessage): The system message for the chat agent.
- model_type (ModelType, optional): The LLM model to use for generating
- responses. (default :obj:`ModelType.GPT_3_5_TURBO`)
- model_config (BaseConfig, optional): Configuration options for the
- LLM model. (default: :obj:`None`)
+ model (BaseModelBackend, optional): The model backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
api_key (str, optional): The API key for authenticating with the
LLM service. Only OpenAI and Anthropic model supported (default:
:obj:`None`)
@@ -109,8 +108,7 @@ class ChatAgent(BaseAgent):
def __init__(
self,
system_message: BaseMessage,
- model_type: Optional[ModelType] = None,
- model_config: Optional[BaseConfig] = None,
+ model: Optional[BaseModelBackend] = None,
api_key: Optional[str] = None,
memory: Optional[AgentMemory] = None,
message_window_size: Optional[int] = None,
@@ -123,24 +121,30 @@ class ChatAgent(BaseAgent):
self.system_message = system_message
self.role_name: str = system_message.role_name
self.role_type: RoleType = system_message.role_type
+ self._api_key = api_key
+ self.model_backend: BaseModelBackend = (
+ model
+ if model is not None
+ else ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=ChatGPTConfig().__dict__,
+ api_key=self._api_key,
+ )
+ )
self.output_language: Optional[str] = output_language
if self.output_language is not None:
self.set_output_language(self.output_language)
- self.model_type: ModelType = (
- model_type if model_type is not None else ModelType.GPT_3_5_TURBO
- )
+ self.model_type: ModelType = self.model_backend.model_type
self.func_dict: Dict[str, Callable] = {}
if tools is not None:
for func in tools:
self.func_dict[func.get_function_name()] = func.func
- self.model_config = model_config or ChatGPTConfig()
- self._api_key = api_key
- self.model_backend: BaseModelBackend = ModelFactory.create(
- self.model_type, self.model_config.__dict__, self._api_key
- )
+ self.model_config_dict = self.model_backend.model_config_dict
+
self.model_token_limit = token_limit or self.model_backend.token_limit
context_creator = ScoreBasedContextCreator(
self.model_backend.token_counter,
diff --git a/camel/agents/critic_agent.py b/camel/agents/critic_agent.py
index fc8a9faee..e83dd856d 100644
--- a/camel/agents/critic_agent.py
+++ b/camel/agents/critic_agent.py
@@ -20,8 +20,8 @@ from colorama import Fore
from camel.agents.chat_agent import ChatAgent
from camel.memories import AgentMemory
from camel.messages import BaseMessage
+from camel.models import BaseModelBackend
from camel.responses import ChatAgentResponse
-from camel.types import ModelType
from camel.utils import get_first_int, print_text_animated
@@ -31,10 +31,9 @@ class CriticAgent(ChatAgent):
Args:
system_message (BaseMessage): The system message for the critic
agent.
- model_type (ModelType, optional): The LLM model to use for generating
- responses. (default :obj:`ModelType.GPT_3_5_TURBO`)
- model_config (Any, optional): Configuration options for the LLM model.
- (default: :obj:`None`)
+ model (BaseModelBackend, optional): The model backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
message_window_size (int, optional): The maximum number of previous
messages to include in the context window. If `None`, no windowing
is performed. (default: :obj:`6`)
@@ -48,8 +47,7 @@ class CriticAgent(ChatAgent):
def __init__(
self,
system_message: BaseMessage,
- model_type: ModelType = ModelType.GPT_3_5_TURBO,
- model_config: Optional[Any] = None,
+ model: Optional[BaseModelBackend] = None,
memory: Optional[AgentMemory] = None,
message_window_size: int = 6,
retry_attempts: int = 2,
@@ -58,8 +56,7 @@ class CriticAgent(ChatAgent):
) -> None:
super().__init__(
system_message,
- model_type=model_type,
- model_config=model_config,
+ model=model,
memory=memory,
message_window_size=message_window_size,
)
diff --git a/camel/agents/deductive_reasoner_agent.py b/camel/agents/deductive_reasoner_agent.py
index 97d1d3d07..45961a511 100644
--- a/camel/agents/deductive_reasoner_agent.py
+++ b/camel/agents/deductive_reasoner_agent.py
@@ -15,10 +15,10 @@ import re
from typing import Dict, List, Optional, Union
from camel.agents.chat_agent import ChatAgent
-from camel.configs import BaseConfig
from camel.messages import BaseMessage
+from camel.models import BaseModelBackend
from camel.prompts import TextPrompt
-from camel.types import ModelType, RoleType
+from camel.types import RoleType
class DeductiveReasonerAgent(ChatAgent):
@@ -33,16 +33,14 @@ class DeductiveReasonerAgent(ChatAgent):
- L represents the path or process from A to B.
Args:
- model_type (ModelType, optional): The type of model to use for the
- agent. (default: :obj: `None`)
- model_config (BaseConfig, optional): The configuration for the model.
- (default: :obj:`None`)
+ model (BaseModelBackend, optional): The model backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
"""
def __init__(
self,
- model_type: Optional[ModelType] = None,
- model_config: Optional[BaseConfig] = None,
+ model: Optional[BaseModelBackend] = None,
) -> None:
system_message = BaseMessage(
role_name="Insight Agent",
@@ -50,7 +48,7 @@ class DeductiveReasonerAgent(ChatAgent):
meta_dict=None,
content="You assign roles based on tasks.",
)
- super().__init__(system_message, model_type, model_config)
+ super().__init__(system_message, model=model)
def deduce_conditions_and_quality(
self,
diff --git a/camel/agents/embodied_agent.py b/camel/agents/embodied_agent.py
index e05365c11..fab361c34 100644
--- a/camel/agents/embodied_agent.py
+++ b/camel/agents/embodied_agent.py
@@ -23,8 +23,8 @@ from camel.interpreters import (
SubprocessInterpreter,
)
from camel.messages import BaseMessage
+from camel.models import BaseModelBackend
from camel.responses import ChatAgentResponse
-from camel.types import ModelType
from camel.utils import print_text_animated
@@ -33,10 +33,9 @@ class EmbodiedAgent(ChatAgent):
Args:
system_message (BaseMessage): The system message for the chat agent.
- model_type (ModelType, optional): The LLM model to use for generating
- responses. (default :obj:`ModelType.GPT_4`)
- model_config (Any, optional): Configuration options for the LLM model.
- (default: :obj:`None`)
+ model (BaseModelBackend, optional): The model backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
message_window_size (int, optional): The maximum number of previous
messages to include in the context window. If `None`, no windowing
is performed. (default: :obj:`None`)
@@ -55,8 +54,7 @@ class EmbodiedAgent(ChatAgent):
def __init__(
self,
system_message: BaseMessage,
- model_type: ModelType = ModelType.GPT_4,
- model_config: Optional[Any] = None,
+ model: Optional[BaseModelBackend] = None,
message_window_size: Optional[int] = None,
tool_agents: Optional[List[BaseToolAgent]] = None,
code_interpreter: Optional[BaseInterpreter] = None,
@@ -78,8 +76,7 @@ class EmbodiedAgent(ChatAgent):
self.logger_color = logger_color
super().__init__(
system_message=system_message,
- model_type=model_type,
- model_config=model_config,
+ model=model,
message_window_size=message_window_size,
)
diff --git a/camel/agents/knowledge_graph_agent.py b/camel/agents/knowledge_graph_agent.py
index fd4c74339..177e17055 100644
--- a/camel/agents/knowledge_graph_agent.py
+++ b/camel/agents/knowledge_graph_agent.py
@@ -11,19 +11,20 @@
# 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, Optional, Union
+from typing import Optional, Union
from unstructured.documents.elements import Element
from camel.agents import ChatAgent
from camel.messages import BaseMessage
+from camel.models import BaseModelBackend
from camel.prompts import TextPrompt
from camel.storages.graph_storages.graph_element import (
GraphElement,
Node,
Relationship,
)
-from camel.types import ModelType, RoleType
+from camel.types import RoleType
text_prompt = """
You are tasked with extracting nodes and relationships from given content and
@@ -105,16 +106,14 @@ class KnowledgeGraphAgent(ChatAgent):
def __init__(
self,
- model_type: ModelType = ModelType.GPT_3_5_TURBO,
- model_config: Optional[Any] = None,
+ model: Optional[BaseModelBackend] = None,
) -> None:
r"""Initialize the `KnowledgeGraphAgent`.
Args:
- model_type (ModelType, optional): The type of model to use for the
- agent. Defaults to `ModelType.GPT_3_5_TURBO`.
- model_config (Any, optional): The configuration for the model.
- Defaults to `None`.
+ model (BaseModelBackend, optional): The model backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
"""
system_message = BaseMessage(
role_name="Graphify",
@@ -126,7 +125,7 @@ class KnowledgeGraphAgent(ChatAgent):
"illuminate the hidden connections within the chaos of "
"information.",
)
- super().__init__(system_message, model_type, model_config)
+ super().__init__(system_message, model=model)
def run(
self,
diff --git a/camel/agents/role_assignment_agent.py b/camel/agents/role_assignment_agent.py
index 38be7e1c3..50f059826 100644
--- a/camel/agents/role_assignment_agent.py
+++ b/camel/agents/role_assignment_agent.py
@@ -12,32 +12,31 @@
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
import re
-from typing import Any, Dict, Optional, Union
+from typing import Dict, Optional, Union
from camel.agents.chat_agent import ChatAgent
from camel.messages import BaseMessage
+from camel.models import BaseModelBackend
from camel.prompts import TextPrompt
-from camel.types import ModelType, RoleType
+from camel.types import RoleType
class RoleAssignmentAgent(ChatAgent):
r"""An agent that generates role names based on the task prompt.
+ Args:
+ model (BaseModelBackend, optional): The model backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
+
Attributes:
role_assignment_prompt (TextPrompt): A prompt for the agent to generate
role names.
-
- Args:
- model_type (ModelType, optional): The type of model to use for the
- agent. (default: :obj:`ModelType.GPT_3_5_TURBO`)
- model_config (Any, optional): The configuration for the model.
- (default: :obj:`None`)
"""
def __init__(
self,
- model_type: ModelType = ModelType.GPT_3_5_TURBO,
- model_config: Optional[Any] = None,
+ model: Optional[BaseModelBackend] = None,
) -> None:
system_message = BaseMessage(
role_name="Role Assigner",
@@ -45,7 +44,7 @@ class RoleAssignmentAgent(ChatAgent):
meta_dict=None,
content="You assign roles based on tasks.",
)
- super().__init__(system_message, model_type, model_config)
+ super().__init__(system_message, model=model)
def run(
self,
diff --git a/camel/agents/search_agent.py b/camel/agents/search_agent.py
index d66c8e1c1..af6e28298 100644
--- a/camel/agents/search_agent.py
+++ b/camel/agents/search_agent.py
@@ -11,12 +11,13 @@
# 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, Optional
+from typing import Optional
from camel.agents.chat_agent import ChatAgent
from camel.messages import BaseMessage
+from camel.models import BaseModelBackend
from camel.prompts import TextPrompt
-from camel.types import ModelType, RoleType
+from camel.types import RoleType
from camel.utils import create_chunks
@@ -33,8 +34,7 @@ class SearchAgent(ChatAgent):
def __init__(
self,
- model_type: ModelType = ModelType.GPT_3_5_TURBO,
- model_config: Optional[Any] = None,
+ model: Optional[BaseModelBackend] = None,
) -> None:
system_message = BaseMessage(
role_name="Assistant",
@@ -42,7 +42,7 @@ class SearchAgent(ChatAgent):
meta_dict=None,
content="You are a helpful assistant.",
)
- super().__init__(system_message, model_type, model_config)
+ super().__init__(system_message, model=model)
def summarize_text(self, text: str, query: str) -> str:
r"""Summarize the information from the text, base on the query.
diff --git a/camel/agents/task_agent.py b/camel/agents/task_agent.py
index db6d46879..cffaa281f 100644
--- a/camel/agents/task_agent.py
+++ b/camel/agents/task_agent.py
@@ -14,10 +14,10 @@
from typing import Any, Dict, List, Optional, Union
from camel.agents.chat_agent import ChatAgent
-from camel.configs import ChatGPTConfig
from camel.messages import BaseMessage
+from camel.models import BaseModelBackend
from camel.prompts import PromptTemplateGenerator, TextPrompt
-from camel.types import ModelType, RoleType, TaskType
+from camel.types import RoleType, TaskType
from camel.utils import get_task_list
@@ -30,27 +30,25 @@ class TaskSpecifyAgent(ChatAgent):
task_specify_prompt (TextPrompt): The prompt for specifying the task.
Args:
- model_type (ModelType, optional): The type of model to use for the
- agent. (default: :obj:`ModelType.GPT_3_5_TURBO`)
+ model (BaseModelBackend, optional): The model backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
task_type (TaskType, optional): The type of task for which to generate
a prompt. (default: :obj:`TaskType.AI_SOCIETY`)
- model_config (Any, optional): The configuration for the model.
- (default: :obj:`None`)
task_specify_prompt (Union[str, TextPrompt], optional): The prompt for
specifying the task. (default: :obj:`None`)
word_limit (int, optional): The word limit for the task prompt.
(default: :obj:`50`)
output_language (str, optional): The language to be output by the
- agent. (default: :obj:`None`)
+ agent. (default: :obj:`None`)
"""
DEFAULT_WORD_LIMIT = 50
def __init__(
self,
- model_type: Optional[ModelType] = None,
+ model: Optional[BaseModelBackend] = None,
task_type: TaskType = TaskType.AI_SOCIETY,
- model_config: Optional[Any] = None,
task_specify_prompt: Optional[Union[str, TextPrompt]] = None,
word_limit: int = DEFAULT_WORD_LIMIT,
output_language: Optional[str] = None,
@@ -67,8 +65,6 @@ class TaskSpecifyAgent(ChatAgent):
else:
self.task_specify_prompt = TextPrompt(task_specify_prompt)
- model_config = model_config or ChatGPTConfig(temperature=1.0)
-
system_message = BaseMessage(
role_name="Task Specifier",
role_type=RoleType.ASSISTANT,
@@ -78,8 +74,7 @@ class TaskSpecifyAgent(ChatAgent):
super().__init__(
system_message,
- model_type=model_type,
- model_config=model_config,
+ model=model,
output_language=output_language,
)
@@ -130,18 +125,16 @@ class TaskPlannerAgent(ChatAgent):
the task into subtasks.
Args:
- model_type (ModelType, optional): The type of model to use for the
- agent. (default: :obj:`ModelType.GPT_3_5_TURBO`)
- model_config (Any, optional): The configuration for the model.
- (default: :obj:`None`)
+ model (BaseModelBackend, optional): The model backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
output_language (str, optional): The language to be output by the
- agent. (default: :obj:`None`)
+ agent. (default: :obj:`None`)
"""
def __init__(
self,
- model_type: Optional[ModelType] = None,
- model_config: Optional[Any] = None,
+ model: Optional[BaseModelBackend] = None,
output_language: Optional[str] = None,
) -> None:
self.task_planner_prompt = TextPrompt(
@@ -156,8 +149,7 @@ class TaskPlannerAgent(ChatAgent):
super().__init__(
system_message,
- model_type,
- model_config,
+ model=model,
output_language=output_language,
)
@@ -208,10 +200,9 @@ class TaskCreationAgent(ChatAgent):
role_name (str): The role name of the Agent to create the task.
objective (Union[str, TextPrompt]): The objective of the Agent to
perform the task.
- model_type (ModelType, optional): The type of model to use for the
- agent. (default: :obj:`ModelType.GPT_3_5_TURBO`)
- model_config (Any, optional): The configuration for the model.
- (default: :obj:`None`)
+ model (BaseModelBackend, optional): The LLM backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
output_language (str, optional): The language to be output by the
agent. (default: :obj:`None`)
message_window_size (int, optional): The maximum number of previous
@@ -225,8 +216,7 @@ class TaskCreationAgent(ChatAgent):
self,
role_name: str,
objective: Union[str, TextPrompt],
- model_type: Optional[ModelType] = None,
- model_config: Optional[Any] = None,
+ model: Optional[BaseModelBackend] = None,
output_language: Optional[str] = None,
message_window_size: Optional[int] = None,
max_task_num: Optional[int] = 3,
@@ -266,8 +256,7 @@ Be concrete.
super().__init__(
system_message,
- model_type,
- model_config,
+ model=model,
output_language=output_language,
message_window_size=message_window_size,
)
@@ -282,6 +271,7 @@ Be concrete.
Args:
task_list (List[str]): The completed or in-progress
tasks which should not overlap with new created tasks.
+
Returns:
List[str]: The new task list generated by the Agent.
"""
@@ -321,10 +311,9 @@ class TaskPrioritizationAgent(ChatAgent):
Args:
objective (Union[str, TextPrompt]): The objective of the Agent to
perform the task.
- model_type (ModelType, optional): The type of model to use for the
- agent. (default: :obj:`ModelType.GPT_3_5_TURBO`)
- model_config (Any, optional): The configuration for the model.
- (default: :obj:`None`)
+ model (BaseModelBackend, optional): The LLM backend to use for
+ generating responses. (default: :obj:`OpenAIModel` with
+ `GPT_3_5_TURBO`)
output_language (str, optional): The language to be output by the
agent. (default: :obj:`None`)
message_window_size (int, optional): The maximum number of previous
@@ -335,8 +324,7 @@ class TaskPrioritizationAgent(ChatAgent):
def __init__(
self,
objective: Union[str, TextPrompt],
- model_type: Optional[ModelType] = None,
- model_config: Optional[Any] = None,
+ model: Optional[BaseModelBackend] = None,
output_language: Optional[str] = None,
message_window_size: Optional[int] = None,
) -> None:
@@ -372,8 +360,7 @@ with any other output."""
super().__init__(
system_message,
- model_type,
- model_config,
+ model=model,
output_language=output_language,
message_window_size=message_window_size,
)
@@ -386,6 +373,7 @@ with any other output."""
Args:
task_list (List[str]): The unprioritized tasks of agent.
+
Returns:
List[str]: The new prioritized task list generated by the Agent.
"""
diff --git a/camel/models/__init__.py b/camel/models/__init__.py
index 39608471f..fbc4f8cc9 100644
--- a/camel/models/__init__.py
+++ b/camel/models/__init__.py
@@ -15,6 +15,7 @@ from .anthropic_model import AnthropicModel
from .base_model import BaseModelBackend
from .litellm_model import LiteLLMModel
from .model_factory import ModelFactory
+from .ollama_model import OllamaModel
from .open_source_model import OpenSourceModel
from .openai_audio_models import OpenAIAudioModels
from .openai_model import OpenAIModel
@@ -31,4 +32,5 @@ __all__ = [
'ModelFactory',
'LiteLLMModel',
'OpenAIAudioModels',
+ 'OllamaModel',
]
diff --git a/camel/models/anthropic_model.py b/camel/models/anthropic_model.py
index 7dfbb395b..d33a23e63 100644
--- a/camel/models/anthropic_model.py
+++ b/camel/models/anthropic_model.py
@@ -35,6 +35,7 @@ class AnthropicModel(BaseModelBackend):
model_type: ModelType,
model_config_dict: Dict[str, Any],
api_key: Optional[str] = None,
+ url: Optional[str] = None,
) -> None:
r"""Constructor for Anthropic backend.
@@ -45,10 +46,11 @@ class AnthropicModel(BaseModelBackend):
be fed into Anthropic.messages.create().
api_key (Optional[str]): The API key for authenticating with the
Anthropic service. (default: :obj:`None`)
+ url (Optional[str]): The url to the model service.
"""
- super().__init__(model_type, model_config_dict)
+ super().__init__(model_type, model_config_dict, api_key, url)
self._api_key = api_key or os.environ.get("ANTHROPIC_API_KEY")
- self.client = Anthropic(api_key=self._api_key)
+ self.client = Anthropic(api_key=self._api_key, base_url=url)
self._token_counter: Optional[BaseTokenCounter] = None
def _convert_response_from_anthropic_to_openai(self, response):
diff --git a/camel/models/base_model.py b/camel/models/base_model.py
index 0eb899cf6..9937f07ba 100644
--- a/camel/models/base_model.py
+++ b/camel/models/base_model.py
@@ -31,6 +31,7 @@ class BaseModelBackend(ABC):
model_type: ModelType,
model_config_dict: Dict[str, Any],
api_key: Optional[str] = None,
+ url: Optional[str] = None,
) -> None:
r"""Constructor for the model backend.
@@ -38,12 +39,14 @@ class BaseModelBackend(ABC):
model_type (ModelType): Model for which a backend is created.
model_config_dict (Dict[str, Any]): A config dictionary.
api_key (Optional[str]): The API key for authenticating with the
- LLM service.
+ model service.
+ url (Optional[str]): The url to the model service.
"""
self.model_type = model_type
self.model_config_dict = model_config_dict
self._api_key = api_key
+ self._url = url
self.check_model_config()
@property
diff --git a/camel/models/model_factory.py b/camel/models/model_factory.py
index 8f60164fe..86f9978dc 100644
--- a/camel/models/model_factory.py
+++ b/camel/models/model_factory.py
@@ -11,15 +11,17 @@
# 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, Optional
+from typing import Any, Dict, Optional, Union
from camel.models.anthropic_model import AnthropicModel
from camel.models.base_model import BaseModelBackend
+from camel.models.litellm_model import LiteLLMModel
+from camel.models.ollama_model import OllamaModel
from camel.models.open_source_model import OpenSourceModel
from camel.models.openai_model import OpenAIModel
from camel.models.stub_model import StubModel
from camel.models.zhipuai_model import ZhipuAIModel
-from camel.types import ModelType
+from camel.types import ModelPlatformType, ModelType
class ModelFactory:
@@ -31,18 +33,24 @@ class ModelFactory:
@staticmethod
def create(
- model_type: ModelType,
+ model_platform: ModelPlatformType,
+ model_type: Union[ModelType, str],
model_config_dict: Dict,
api_key: Optional[str] = None,
+ url: Optional[str] = None,
) -> BaseModelBackend:
r"""Creates an instance of `BaseModelBackend` of the specified type.
Args:
- model_type (ModelType): Model for which a backend is created.
+ model_platform (ModelPlatformType): Platform from which the model
+ originates.
+ model_type (Union[ModelType, str]): Model for which a backend is
+ created can be a `str` for open source platforms.
model_config_dict (Dict): A dictionary that will be fed into
the backend constructor.
api_key (Optional[str]): The API key for authenticating with the
- LLM service.
+ model service.
+ url (Optional[str]): The url to the model service.
Raises:
ValueError: If there is not backend for the model.
@@ -51,22 +59,35 @@ class ModelFactory:
BaseModelBackend: The initialized backend.
"""
model_class: Any
- if model_type.is_openai:
- model_class = OpenAIModel
- elif model_type == ModelType.STUB:
- model_class = StubModel
- elif model_type.is_open_source:
- model_class = OpenSourceModel
- elif model_type.is_anthropic:
- model_class = AnthropicModel
- elif model_type.is_zhipuai:
- model_class = ZhipuAIModel
- else:
- raise ValueError(f"Unknown model type `{model_type}` is input")
- if model_type.is_open_source:
- inst = model_class(model_type, model_config_dict)
+ if isinstance(model_type, ModelType):
+ if model_platform.is_open_source and model_type.is_open_source:
+ model_class = OpenSourceModel
+ return model_class(model_type, model_config_dict, url)
+ if model_platform.is_openai and model_type.is_openai:
+ model_class = OpenAIModel
+ elif model_platform.is_anthropic and model_type.is_anthropic:
+ model_class = AnthropicModel
+ elif model_platform.is_zhipuai and model_type.is_zhipuai:
+ model_class = ZhipuAIModel
+ elif model_type == ModelType.STUB:
+ model_class = StubModel
+ else:
+ raise ValueError(
+ f"Unknown pair of model platform `{model_platform}` "
+ f"and model type `{model_type}`."
+ )
+ elif isinstance(model_type, str):
+ if model_platform.is_ollama:
+ model_class = OllamaModel
+ elif model_platform.is_litellm:
+ model_class = LiteLLMModel
+ else:
+ raise ValueError(
+ f"Unknown pair of model platform `{model_platform}` "
+ f"and model type `{model_type}`."
+ )
else:
- inst = model_class(model_type, model_config_dict, api_key)
+ raise ValueError(f"Invalid model type `{model_type}` provided.")
- return inst
+ return model_class(model_type, model_config_dict, api_key, url)
diff --git a/camel/models/ollama_model.py b/camel/models/ollama_model.py
new file mode 100644
index 000000000..9fc8b0178
--- /dev/null
+++ b/camel/models/ollama_model.py
@@ -0,0 +1,121 @@
+# =========== 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 os
+from typing import Any, Dict, List, Optional, Union
+
+from openai import OpenAI, Stream
+
+from camel.configs import OPENAI_API_PARAMS
+from camel.messages import OpenAIMessage
+from camel.types import ChatCompletion, ChatCompletionChunk, ModelType
+from camel.utils import BaseTokenCounter, OpenAITokenCounter
+
+
+class OllamaModel:
+ r"""Ollama service interface."""
+
+ # NOTE: Current `ModelType and `TokenCounter` desigen is not suitable,
+ # stream mode is not supported
+
+ def __init__(
+ self,
+ model_type: str,
+ model_config_dict: Dict[str, Any],
+ api_key: Optional[str] = None,
+ url: Optional[str] = None,
+ ) -> None:
+ r"""Constructor for Ollama backend with OpenAI compatibility.
+
+ Args:
+ model_type (str): Model for which a backend is created.
+ model_config_dict (Dict[str, Any]): A dictionary that will
+ be fed into openai.ChatCompletion.create().
+ api_key (Optional[str]): The API key for authenticating with the
+ model service. (default: :obj:`None`)
+ url (Optional[str]): The url to the model service.
+ """
+ self.model_type = model_type
+ self.model_config_dict = model_config_dict
+ self._url = url or os.environ.get('OPENAI_API_BASE_URL')
+ self._api_key = api_key or os.environ.get("OPENAI_API_KEY")
+ # Use OpenAI cilent as interface call Ollama
+ # Reference: https://github.com/ollama/ollama/blob/main/docs/openai.md
+ self._client = OpenAI(
+ timeout=60,
+ max_retries=3,
+ base_url=self._url,
+ api_key=self._api_key,
+ )
+ 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.
+ """
+ # NOTE: Use OpenAITokenCounter temporarily
+ if not self._token_counter:
+ self._token_counter = OpenAITokenCounter(ModelType.GPT_3_5_TURBO)
+ return self._token_counter
+
+ 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:
+ raise ValueError(
+ f"Unexpected argument `{param}` is "
+ "input into OpenAI model backend."
+ )
+
+ def run(
+ self,
+ messages: List[OpenAIMessage],
+ ) -> 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.
+
+ Returns:
+ Union[ChatCompletion, Stream[ChatCompletionChunk]]:
+ `ChatCompletion` in the non-stream mode, or
+ `Stream[ChatCompletionChunk]` in the stream mode.
+ """
+
+ response = self._client.chat.completions.create(
+ messages=messages,
+ model=self.model_type,
+ **self.model_config_dict,
+ )
+ return response
+
+ @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/open_source_model.py b/camel/models/open_source_model.py
index 487f7edb3..35a74ef14 100644
--- a/camel/models/open_source_model.py
+++ b/camel/models/open_source_model.py
@@ -31,6 +31,8 @@ class OpenSourceModel(BaseModelBackend):
self,
model_type: ModelType,
model_config_dict: Dict[str, Any],
+ api_key: Optional[str] = None,
+ url: Optional[str] = None,
) -> None:
r"""Constructor for model backends of Open-source models.
@@ -38,8 +40,11 @@ class OpenSourceModel(BaseModelBackend):
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()`.
+ api_key (Optional[str]): The API key for authenticating with the
+ model service. (ignored for open-source models)
+ url (Optional[str]): The url to the model service.
"""
- super().__init__(model_type, model_config_dict)
+ super().__init__(model_type, model_config_dict, api_key, url)
self._token_counter: Optional[BaseTokenCounter] = None
# Check whether the input model type is open-source
@@ -65,7 +70,7 @@ class OpenSourceModel(BaseModelBackend):
)
# Load the server URL and check whether it is None
- server_url: Optional[str] = self.model_config_dict.get(
+ server_url: Optional[str] = url or self.model_config_dict.get(
"server_url", None
)
if not server_url:
diff --git a/camel/models/openai_model.py b/camel/models/openai_model.py
index 9a981ecd5..ddfe86d7f 100644
--- a/camel/models/openai_model.py
+++ b/camel/models/openai_model.py
@@ -35,6 +35,7 @@ class OpenAIModel(BaseModelBackend):
model_type: ModelType,
model_config_dict: Dict[str, Any],
api_key: Optional[str] = None,
+ url: Optional[str] = None,
) -> None:
r"""Constructor for OpenAI backend.
@@ -45,12 +46,16 @@ class OpenAIModel(BaseModelBackend):
be fed into openai.ChatCompletion.create().
api_key (Optional[str]): The API key for authenticating with the
OpenAI service. (default: :obj:`None`)
+ url (Optional[str]): The url to the OpenAI service.
"""
- super().__init__(model_type, model_config_dict)
- url = os.environ.get('OPENAI_API_BASE_URL', None)
+ super().__init__(model_type, model_config_dict, api_key, url)
+ self._url = url or os.environ.get("OPENAI_API_BASE_URL")
self._api_key = api_key or os.environ.get("OPENAI_API_KEY")
self._client = OpenAI(
- timeout=60, max_retries=3, base_url=url, api_key=self._api_key
+ timeout=60,
+ max_retries=3,
+ base_url=self._url,
+ api_key=self._api_key,
)
self._token_counter: Optional[BaseTokenCounter] = None
diff --git a/camel/models/stub_model.py b/camel/models/stub_model.py
index ad53649b3..291fc02b3 100644
--- a/camel/models/stub_model.py
+++ b/camel/models/stub_model.py
@@ -54,11 +54,13 @@ class StubModel(BaseModelBackend):
model_type: ModelType,
model_config_dict: Dict[str, Any],
api_key: Optional[str] = None,
+ url: Optional[str] = None,
) -> None:
r"""All arguments are unused for the dummy model."""
- super().__init__(model_type, model_config_dict)
+ super().__init__(model_type, model_config_dict, api_key, url)
self._token_counter: Optional[BaseTokenCounter] = None
self._api_key = api_key
+ self._url = url
@property
def token_counter(self) -> BaseTokenCounter:
diff --git a/camel/societies/role_playing.py b/camel/societies/role_playing.py
index e4558afe3..b2fd410e4 100644
--- a/camel/societies/role_playing.py
+++ b/camel/societies/role_playing.py
@@ -22,9 +22,10 @@ from camel.agents import (
from camel.generators import SystemMessageGenerator
from camel.human import Human
from camel.messages import BaseMessage
+from camel.models import BaseModelBackend
from camel.prompts import TextPrompt
from camel.responses import ChatAgentResponse
-from camel.types import ModelType, RoleType, TaskType
+from camel.types import RoleType, TaskType
class RolePlaying:
@@ -48,9 +49,9 @@ class RolePlaying:
in the loop. (default: :obj:`False`)
critic_criteria (str, optional): Critic criteria for the critic agent.
If not specified, set the criteria to improve task performance.
- model_type (ModelType, optional): Model type that will be used for
- role playing. If specified, it will override the model in all
- agents. (default: :obj:`None`)
+ model (BaseModelBackend, optional): The model backend to use for
+ generating responses. If specified, it will override the model in
+ all agents. (default: :obj:`None`)
task_type (TaskType, optional): The type of task to perform.
(default: :obj:`TaskType.AI_SOCIETY`)
assistant_agent_kwargs (Dict, optional): Additional arguments to pass
@@ -84,7 +85,7 @@ class RolePlaying:
with_task_planner: bool = False,
with_critic_in_the_loop: bool = False,
critic_criteria: Optional[str] = None,
- model_type: Optional[ModelType] = None,
+ model: Optional[BaseModelBackend] = None,
task_type: TaskType = TaskType.AI_SOCIETY,
assistant_agent_kwargs: Optional[Dict] = None,
user_agent_kwargs: Optional[Dict] = None,
@@ -99,7 +100,7 @@ class RolePlaying:
self.with_task_specify = with_task_specify
self.with_task_planner = with_task_planner
self.with_critic_in_the_loop = with_critic_in_the_loop
- self.model_type = model_type
+ self.model = model
self.task_type = task_type
self.task_prompt = task_prompt
@@ -189,12 +190,10 @@ class RolePlaying:
)
)
task_specify_meta_dict.update(extend_task_specify_meta_dict or {})
- if self.model_type is not None:
+ if self.model is not None:
if task_specify_agent_kwargs is None:
task_specify_agent_kwargs = {}
- task_specify_agent_kwargs.update(
- dict(model_type=self.model_type)
- )
+ task_specify_agent_kwargs.update(dict(model=self.model))
task_specify_agent = TaskSpecifyAgent(
task_type=self.task_type,
output_language=output_language,
@@ -224,12 +223,10 @@ class RolePlaying:
agents. (default: :obj:`None`)
"""
if self.with_task_planner:
- if self.model_type is not None:
+ if self.model is not None:
if task_planner_agent_kwargs is None:
task_planner_agent_kwargs = {}
- task_planner_agent_kwargs.update(
- dict(model_type=self.model_type)
- )
+ task_planner_agent_kwargs.update(dict(model=self.model))
task_planner_agent = TaskPlannerAgent(
output_language=output_language,
**(task_planner_agent_kwargs or {}),
@@ -321,13 +318,13 @@ class RolePlaying:
output_language (str, optional): The language to be output by the
agents. (default: :obj:`None`)
"""
- if self.model_type is not None:
+ if self.model is not None:
if assistant_agent_kwargs is None:
assistant_agent_kwargs = {}
- assistant_agent_kwargs.update(dict(model_type=self.model_type))
+ assistant_agent_kwargs.update(dict(model=self.model))
if user_agent_kwargs is None:
user_agent_kwargs = {}
- user_agent_kwargs.update(dict(model_type=self.model_type))
+ user_agent_kwargs.update(dict(model=self.model))
self.assistant_agent = ChatAgent(
init_assistant_sys_msg,
@@ -383,10 +380,10 @@ class RolePlaying:
critic_msg_meta_dict,
role_tuple=(critic_role_name, RoleType.CRITIC),
)
- if self.model_type is not None:
+ if self.model is not None:
if critic_kwargs is None:
critic_kwargs = {}
- critic_kwargs.update(dict(model_type=self.model_type))
+ critic_kwargs.update(dict(model=self.model))
self.critic = CriticAgent(
self.critic_sys_msg,
**(critic_kwargs or {}),
diff --git a/camel/types/__init__.py b/camel/types/__init__.py
index 39542fdb6..5228436ec 100644
--- a/camel/types/__init__.py
+++ b/camel/types/__init__.py
@@ -14,6 +14,7 @@
from .enums import (
AudioModelType,
EmbeddingModelType,
+ ModelPlatformType,
ModelType,
OpenAIBackendRole,
OpenAIImageType,
@@ -62,6 +63,7 @@ __all__ = [
'OpenAIImageType',
'OpenAIVisionDetailType',
'OpenAPIName',
+ 'ModelPlatformType',
'AudioModelType',
'VoiceType',
]
diff --git a/camel/types/enums.py b/camel/types/enums.py
index 424da95da..a51b9bc06 100644
--- a/camel/types/enums.py
+++ b/camel/types/enums.py
@@ -52,7 +52,11 @@ class ModelType(Enum):
@property
def value_for_tiktoken(self) -> str:
- return self.value if self is not ModelType.STUB else "gpt-3.5-turbo"
+ return (
+ self.value
+ if self is not ModelType.STUB and not isinstance(self, str)
+ else "gpt-3.5-turbo"
+ )
@property
def is_openai(self) -> bool:
@@ -280,6 +284,52 @@ class OpenAPIName(Enum):
WEB_SCRAPER = "web_scraper"
+class ModelPlatformType(Enum):
+ OPENAI = "openai"
+ AZURE = "azure"
+ ANTHROPIC = "anthropic"
+ OPENSOURCE = "opensource"
+ OLLAMA = "ollama"
+ LITELLM = "litellm"
+ ZHIPU = "zhipuai"
+ DEFAULT = "default"
+
+ @property
+ def is_openai(self) -> bool:
+ r"""Returns whether this platform is openai."""
+ return self is ModelPlatformType.OPENAI
+
+ @property
+ def is_azure(self) -> bool:
+ r"""Returns whether this platform is azure."""
+ return self is ModelPlatformType.AZURE
+
+ @property
+ def is_anthropic(self) -> bool:
+ r"""Returns whether this platform is anthropic."""
+ return self is ModelPlatformType.ANTHROPIC
+
+ @property
+ def is_ollama(self) -> bool:
+ r"""Returns whether this platform is ollama."""
+ return self is ModelPlatformType.OLLAMA
+
+ @property
+ def is_litellm(self) -> bool:
+ r"""Returns whether this platform is litellm."""
+ return self is ModelPlatformType.LITELLM
+
+ @property
+ def is_zhipuai(self) -> bool:
+ r"""Returns whether this platform is zhipu."""
+ return self is ModelPlatformType.ZHIPU
+
+ @property
+ def is_open_source(self) -> bool:
+ r"""Returns whether this platform is opensource."""
+ return self is ModelPlatformType.OPENSOURCE
+
+
class AudioModelType(Enum):
TTS_1 = "tts-1"
TTS_1_HD = "tts-1-hd"
diff --git a/docs/agents/critic_agents_and_tree_search.md b/docs/agents/critic_agents_and_tree_search.md
index 6396c9e2f..83f9e0f8e 100644
--- a/docs/agents/critic_agents_and_tree_search.md
+++ b/docs/agents/critic_agents_and_tree_search.md
@@ -76,36 +76,41 @@ Our `RolePlaying()` class provide a simple way for you to add the critic in the
# Import necessary classes
from camel.societies import RolePlaying
from camel.configs import ChatGPTConfig
-from camel.types import TaskType, ModelType
+from camel.types import TaskType, ModelType, ModelPlatformType
from colorama import Fore
from camel.utils import print_text_animated
+from camel.models import ModelFactory
# Set the LLM model type and model config
+model_platform = ModelPlatformType.OPENAI
model_type = ModelType.GPT_3_5_TURBO
model_config = ChatGPTConfig(
temperature=0.8, # the sampling temperature; the higher the more random
n=3, # the no. of completion choices to generate for each input
)
+
+# Create the backend model
+model = ModelFactory.create(
+ model_platform=model_platform,
+ model_type=model_type,
+ model_config=model_config)
```
We then need to set the kwargs for the task and each agent:
```python
task_kwargs = {
'task_prompt': 'Develop a plan to TRAVEL TO THE PAST and make changes.',
'with_task_specify': True,
- 'task_specify_agent_kwargs': {'model_type': model_type,
- 'model_config': model_config}
+ 'task_specify_agent_kwargs': {'model': model}
}
user_role_kwargs = {
'user_role_name': 'an ambitious aspiring TIME TRAVELER',
- 'user_agent_kwargs': {'model_type': model_type,
- 'model_config': model_config}
+ 'user_agent_kwargs': {'model': model}
}
assistant_role_kwargs = {
'assistant_role_name': 'the best-ever experimental physicist',
- 'assistant_agent_kwargs': {'model_type': model_type,
- 'model_config': model_config}
+ 'assistant_agent_kwargs': {'model': model}
}
critic_role_kwargs = {
diff --git a/docs/agents/role_playing.md b/docs/agents/role_playing.md
index 190cc7150..6b3ec8ee6 100644
--- a/docs/agents/role_playing.md
+++ b/docs/agents/role_playing.md
@@ -20,10 +20,22 @@ In this section, we will take a spite of the task-oriented `RolyPlaying()` class
```python
# Import necessary classes
from camel.societies import RolePlaying
-from camel.types import TaskType, ModelType
+from camel.types import TaskType, ModelType, ModelPlatformType
+from camel.models import ModelFactory
-# Set the LLM model type to use
+# Set the LLM model type and model config
+model_platform = ModelPlatformType.OPENAI
model_type = ModelType.GPT_3_5_TURBO
+model_config = ChatGPTConfig(
+ temperature=0.8, # the sampling temperature; the higher the more random
+ n=3, # the no. of completion choices to generate for each input
+ )
+
+# Create the backend model
+model = ModelFactory.create(
+ model_platform=model_platform,
+ model_type=model_type,
+ model_config=model_config)
```
### Step 1: Configure the Role-Playing Session
@@ -32,7 +44,7 @@ model_type = ModelType.GPT_3_5_TURBO
task_kwargs = {
'task_prompt': 'Develop a plan to TRAVEL TO THE PAST and make changes.',
'with_task_specify': True,
- 'task_specify_agent_kwargs': {'model_type': model_type}
+ 'task_specify_agent_kwargs': {'model': model}
}
```
@@ -41,7 +53,7 @@ You may think the user as the `instruction sender`.
```python
user_role_kwargs = {
'user_role_name': 'an ambitious aspiring TIME TRAVELER',
- 'user_agent_kwargs': {'model_type': model_type}
+ 'user_agent_kwargs': {'model': model}
}
```
@@ -50,7 +62,7 @@ Again, you may think the assistant as the `instruction executor`.
```python
assistant_role_kwargs = {
'assistant_role_name': 'the best-ever experimental physicist',
- 'assistant_agent_kwargs': {'model_type': model_type}
+ 'assistant_agent_kwargs': {'model': model}
}
```
diff --git a/docs/agents/single_agent.md b/docs/agents/single_agent.md
index f367fd49f..4077fe9ff 100644
--- a/docs/agents/single_agent.md
+++ b/docs/agents/single_agent.md
@@ -115,22 +115,29 @@ You can connect the agent with external database (as long-term memory) in which
...
# Import the necessary classes
- from camel.configs import OpenSourceConfig
- from camel.types import ModelType
- # Set the arguments
- agent_kwargs = dict(
- model_type=ModelType.LLAMA_2, # Specify the model type
+ from camel.configs import ChatGPTConfig, OpenSourceConfig
+ from camel.types import ModelType, ModelPlatformType
+ from camel.models import ModelFactory
- model_config=OpenSourceConfig(
- model_path='meta-llama/Llama-2-7b-chat-hf', # a local folder or HuggingFace repo Name
- server_url='http://localhost:8000/v1')) # The url with the set port number
+ # Set the LLM model type and model config
+ model_platform = ModelPlatformType.OPENSOURCE
+ model_type = ModelType.LLAMA_2
+ model_config=OpenSourceConfig(
+ model_path='meta-llama/Llama-2-7b-chat-hf', # a local folder or HuggingFace repo Name
+ server_url='http://localhost:8000/v1') # The url with the set port number
+
+ # Create the backend model
+ model = ModelFactory.create(
+ model_platform=model_platform,
+ model_type=model_type,
+ model_config=model_config)
# Set the agent
- agent = ChatAgent(sys_msg, **agent_kwargs)
+ agent = ChatAgent(sys_msg, model=model)
```
-- The `ChatAgent` class offers several useful initialization options, including `model_type`, `model_config`, `memory`, `message_window_size`, `token_limit`, `output_language`, `tools`, and `response_terminators`. Check [`chat_agent.py`](https://github.com/camel-ai/camel/blob/master/camel/agents/chat_agent.py) for detailed usage guidance.
+- The `ChatAgent` class offers several useful initialization options, including `model`, `memory`, `message_window_size`, `token_limit`, `output_language`, `tools`, and `response_terminators`. Check [`chat_agent.py`](https://github.com/camel-ai/camel/blob/master/camel/agents/chat_agent.py) for detailed usage guidance.
## Remarks
diff --git a/docs/get_started/setup.md b/docs/get_started/setup.md
index 63a5866d8..bf06eebc8 100644
--- a/docs/get_started/setup.md
+++ b/docs/get_started/setup.md
@@ -139,17 +139,25 @@ The high-level idea is to deploy a server with the local model in the backend an
```python
# Import the necessary classes
from camel.configs import ChatGPTConfig, OpenSourceConfig
- from camel.types import ModelType
+ from camel.types import ModelType, ModelPlatformType
+ from camel.models import ModelFactory
+
+ # Set the LLM model type and model config
+ model_platform = ModelPlatformType.OPENSOURCE
+ model_type=ModelType.LLAMA_2 # Specify the model type
+ model_config=OpenSourceConfig(
+ model_path='meta-llama/Llama-2-7b-chat-hf', # a local folder or HuggingFace repo Name
+ server_url='http://localhost:8000/v1') # The url with the set port number
+
+ # Create the backend model
+ model = ModelFactory.create(
+ model_platform=model_platform,
+ model_type=model_type,
+ model_config=model_config)
# Set the arguments
agent_kwargs = dict(
- model_type=ModelType.LLAMA_2, # Specify the model type
-
- model_config=OpenSourceConfig(
- model_path='meta-llama/Llama-2-7b-chat-hf', # a local folder or HuggingFace repo Name
- server_url='http://localhost:8000/v1', # The url with the set port number
- ),
-
+ model=model,
token_limit=2046, # [Optional] Choose the ideal limit
)
diff --git a/examples/ai_society/babyagi_playing.py b/examples/ai_society/babyagi_playing.py
index 643e38515..0b3361bac 100644
--- a/examples/ai_society/babyagi_playing.py
+++ b/examples/ai_society/babyagi_playing.py
@@ -18,14 +18,14 @@ from camel.societies import BabyAGI
from camel.utils import print_text_animated
-def main(model_type=None, chat_turn_limit=15) -> None:
+def main(model=None, chat_turn_limit=15) -> None:
task_prompt = "Develop a trading bot for the stock market"
babyagi_session = BabyAGI(
assistant_role_name="Python Programmer",
- assistant_agent_kwargs=dict(model_type=model_type),
+ assistant_agent_kwargs=dict(model=model),
user_role_name="Stock Trader",
task_prompt=task_prompt,
- task_specify_agent_kwargs=dict(model_type=model_type),
+ task_specify_agent_kwargs=dict(model=model),
message_window_size=5,
)
diff --git a/examples/ai_society/role_playing.py b/examples/ai_society/role_playing.py
index 6fea7508f..0ccffab00 100644
--- a/examples/ai_society/role_playing.py
+++ b/examples/ai_society/role_playing.py
@@ -17,16 +17,16 @@ from camel.societies import RolePlaying
from camel.utils import print_text_animated
-def main(model_type=None, chat_turn_limit=50) -> None:
+def main(model=None, chat_turn_limit=50) -> None:
task_prompt = "Develop a trading bot for the stock market"
role_play_session = RolePlaying(
assistant_role_name="Python Programmer",
- assistant_agent_kwargs=dict(model_type=model_type),
+ assistant_agent_kwargs=dict(model=model),
user_role_name="Stock Trader",
- user_agent_kwargs=dict(model_type=model_type),
+ user_agent_kwargs=dict(model=model),
task_prompt=task_prompt,
with_task_specify=True,
- task_specify_agent_kwargs=dict(model_type=model_type),
+ task_specify_agent_kwargs=dict(model=model),
)
print(
diff --git a/examples/ai_society/role_playing_multi_lingual.py b/examples/ai_society/role_playing_multi_lingual.py
index f25786eba..0140e7f79 100644
--- a/examples/ai_society/role_playing_multi_lingual.py
+++ b/examples/ai_society/role_playing_multi_lingual.py
@@ -17,16 +17,16 @@ from camel.societies import RolePlaying
from camel.utils import print_text_animated
-def main(model_type=None) -> None:
+def main(model=None) -> None:
task_prompt = "Develop a trading bot for the stock market"
role_play_session = RolePlaying(
assistant_role_name="Python Programmer",
- assistant_agent_kwargs=dict(model_type=model_type),
+ assistant_agent_kwargs=dict(model=model),
user_role_name="Stock Trader",
- user_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO),
+ user_agent_kwargs=dict(model=model),
task_prompt=task_prompt,
with_task_specify=True,
- task_specify_agent_kwargs=dict(model_type=model_type),
+ task_specify_agent_kwargs=dict(model=model),
output_language="Chinese", # Arabic, French, Spanish, ...
)
diff --git a/examples/ai_society/task_generation.py b/examples/ai_society/task_generation.py
index 779079e03..f19271a85 100644
--- a/examples/ai_society/task_generation.py
+++ b/examples/ai_society/task_generation.py
@@ -35,7 +35,7 @@ def generate_tasks(
assistant_sys_msg = sys_msg_generator.from_dict(
dict(), role_tuple=("Task Generator", RoleType.DEFAULT)
)
- assistant_agent = ChatAgent(assistant_sys_msg, model_type=model)
+ assistant_agent = ChatAgent(assistant_sys_msg, model=model)
user_msg = BaseMessage.make_user_message(
role_name="Task Generator", content=task_generator_prompt
diff --git a/examples/anthropic_models/role_playing_with_claude.py b/examples/anthropic_models/role_playing_with_claude.py
index 1fcae4fbf..aae0ae790 100644
--- a/examples/anthropic_models/role_playing_with_claude.py
+++ b/examples/anthropic_models/role_playing_with_claude.py
@@ -14,8 +14,9 @@
from colorama import Fore
from camel.configs import AnthropicConfig
+from camel.models import ModelFactory
from camel.societies import RolePlaying
-from camel.types import ModelType
+from camel.types import ModelPlatformType, ModelType
from camel.utils import print_text_animated
@@ -23,7 +24,8 @@ def main(model_type=None) -> None:
task_prompt = "Develop a trading bot for the stock market"
agent_kwargs = {
- role: dict(
+ role: ModelFactory.create(
+ model_platform=ModelPlatformType.ANTHROPIC,
model_type=model_type,
model_config=AnthropicConfig(),
)
diff --git a/examples/code/generate_meta_data.py b/examples/code/generate_meta_data.py
index fb10bdb22..1fd0cba0c 100644
--- a/examples/code/generate_meta_data.py
+++ b/examples/code/generate_meta_data.py
@@ -27,7 +27,7 @@ def generate_meta_data(meta_data: str, num: int = 50, model=None):
role_name="Assistant",
content="You are a helpful assistant.",
)
- agent = ChatAgent(assistant_sys_msg, model_type=model)
+ agent = ChatAgent(assistant_sys_msg, model=model)
agent.reset()
user_msg = BaseMessage.make_user_message(
diff --git a/examples/code/role_playing.py b/examples/code/role_playing.py
index 5e2ebe1a6..f7d98beb4 100644
--- a/examples/code/role_playing.py
+++ b/examples/code/role_playing.py
@@ -18,19 +18,19 @@ from camel.types import TaskType
from camel.utils import print_text_animated
-def main(model_type=None, chat_turn_limit=50) -> None:
+def main(model=None, chat_turn_limit=50) -> None:
task_prompt = "Develop a poll app"
language = "JavaScript"
domain = "Sociology"
meta_dict = {"language": language, "domain": domain}
role_play_session = RolePlaying(
assistant_role_name=f"{language} Programmer",
- assistant_agent_kwargs=dict(model_type=model_type),
+ assistant_agent_kwargs=dict(model=model),
user_role_name=f"Person working in {domain}",
- user_agent_kwargs=dict(model_type=model_type),
+ user_agent_kwargs=dict(model=model),
task_prompt=task_prompt,
with_task_specify=True,
- task_specify_agent_kwargs=dict(model_type=model_type),
+ task_specify_agent_kwargs=dict(model=model),
task_type=TaskType.CODE,
extend_sys_msg_meta_dicts=[meta_dict, meta_dict],
extend_task_specify_meta_dict=meta_dict,
diff --git a/examples/code/role_playing_multiprocess.py b/examples/code/role_playing_multiprocess.py
index 3675a34ff..68535ae0c 100644
--- a/examples/code/role_playing_multiprocess.py
+++ b/examples/code/role_playing_multiprocess.py
@@ -17,7 +17,6 @@ import os
from typing import Any, Dict
from camel.agents import ChatAgent, TaskSpecifyAgent
-from camel.configs import ChatGPTConfig
from camel.generators import SystemMessageGenerator
from camel.messages import BaseMessage
from camel.types import RoleType, TaskType
@@ -66,7 +65,6 @@ def generate_data(
task_specify_agent = TaskSpecifyAgent(
task_type=TaskType.CODE,
- model_config=ChatGPTConfig(temperature=1.4),
)
specified_task_prompt = task_specify_agent.run(
original_task_prompt,
diff --git a/examples/code/task_generation.py b/examples/code/task_generation.py
index 69a312b82..532e984b8 100644
--- a/examples/code/task_generation.py
+++ b/examples/code/task_generation.py
@@ -32,7 +32,7 @@ def generate_tasks(
assistant_sys_msg = sys_msg_generator.from_dict(
dict(), role_tuple=("Task Generator", RoleType.DEFAULT)
)
- assistant_agent = ChatAgent(assistant_sys_msg, model_type=model)
+ assistant_agent = ChatAgent(assistant_sys_msg, model=model)
user_msg = BaseMessage.make_user_message(
role_name="Task Generator", content=task_generator_prompt
diff --git a/examples/deductive_reasoner_agent/deduce_conditions_and_quality.py b/examples/deductive_reasoner_agent/deduce_conditions_and_quality.py
index 2544bc925..e9ccf2372 100644
--- a/examples/deductive_reasoner_agent/deduce_conditions_and_quality.py
+++ b/examples/deductive_reasoner_agent/deduce_conditions_and_quality.py
@@ -16,15 +16,11 @@ import json
from colorama import Fore
from camel.agents.deductive_reasoner_agent import DeductiveReasonerAgent
-from camel.configs import ChatGPTConfig
-def main(model_type=None) -> None:
+def main(model=None) -> None:
# Construct deductive reasoner agent
- model_config_description = ChatGPTConfig()
- insight_agent = DeductiveReasonerAgent(
- model_type=model_type, model_config=model_config_description
- )
+ insight_agent = DeductiveReasonerAgent(model=model)
starting_state = "The current empty website."
target_state = "A website with search capabilities."
diff --git a/examples/embodiment/hugging_face_tool.py b/examples/embodiment/hugging_face_tool.py
index b3ec3c7ff..8289d5f60 100644
--- a/examples/embodiment/hugging_face_tool.py
+++ b/examples/embodiment/hugging_face_tool.py
@@ -17,7 +17,7 @@ from camel.agents import EmbodiedAgent, HuggingFaceToolAgent
from camel.agents.tool_agents.base import BaseToolAgent
from camel.generators import SystemMessageGenerator
from camel.messages import BaseMessage
-from camel.types import ModelType, RoleType
+from camel.types import RoleType
def main():
@@ -31,7 +31,6 @@ def main():
tool_agents = [
HuggingFaceToolAgent(
'hugging_face_tool_agent',
- model_type=ModelType.GPT_4.value,
remote=True,
)
]
diff --git a/examples/evaluation/single_agent.py b/examples/evaluation/single_agent.py
index 480a80591..1c83ecbbb 100644
--- a/examples/evaluation/single_agent.py
+++ b/examples/evaluation/single_agent.py
@@ -60,7 +60,7 @@ def generate_questions(
role_name="Assistant",
content="You are a helpful assistant.",
)
- agent = ChatAgent(assistant_sys_msg, model_type=model)
+ agent = ChatAgent(assistant_sys_msg, model=model)
agent.reset()
user_msg = BaseMessage.make_user_message(role_name="User", content=prompt)
diff --git a/examples/function_call/github_examples.py b/examples/function_call/github_examples.py
index cfd9ea657..b2c1b74f3 100644
--- a/examples/function_call/github_examples.py
+++ b/examples/function_call/github_examples.py
@@ -19,7 +19,9 @@ from camel.agents import ChatAgent
from camel.configs import ChatGPTConfig
from camel.functions import OpenAIFunction
from camel.messages import BaseMessage
+from camel.models import ModelFactory
from camel.toolkits import GithubToolkit
+from camel.types import ModelPlatformType, ModelType
from camel.utils import print_text_animated
@@ -111,10 +113,14 @@ def solve_issue(
tools=toolkit.get_tools(),
temperature=0.0,
)
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OpenAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config=assistant_model_config,
+ )
agent = ChatAgent(
assistant_sys_msg,
- model_type=model,
- model_config=assistant_model_config,
+ model=model,
tools=toolkit.get_tools(),
)
agent.reset()
diff --git a/examples/function_call/openapi_function.py b/examples/function_call/openapi_function.py
index 5ebcdcb04..6736d6fe4 100644
--- a/examples/function_call/openapi_function.py
+++ b/examples/function_call/openapi_function.py
@@ -15,7 +15,6 @@ from camel.agents import ChatAgent
from camel.configs.openai_config import ChatGPTConfig
from camel.functions import OPENAPI_FUNCS
from camel.messages import BaseMessage
-from camel.types import ModelType
# Define system message
sys_msg = BaseMessage.make_assistant_message(
@@ -32,9 +31,7 @@ model_config = ChatGPTConfig(
# Set agent
camel_agent = ChatAgent(
system_message=sys_msg,
- model_config=model_config,
tools=OPENAPI_FUNCS,
- model_type=ModelType.GPT_4O,
)
camel_agent.reset()
diff --git a/examples/function_call/role_playing_with_functions.py b/examples/function_call/role_playing_with_functions.py
index 30389a293..cb48f9e47 100644
--- a/examples/function_call/role_playing_with_functions.py
+++ b/examples/function_call/role_playing_with_functions.py
@@ -25,8 +25,9 @@ from camel.functions import (
TWITTER_FUNCS,
WEATHER_FUNCS,
)
+from camel.models import ModelFactory
from camel.societies import RolePlaying
-from camel.types import ModelType
+from camel.types import ModelPlatformType, ModelType
from camel.utils import print_text_animated
@@ -57,13 +58,19 @@ def main(model_type=ModelType.GPT_3_5_TURBO, chat_turn_limit=10) -> None:
assistant_role_name="Searcher",
user_role_name="Professor",
assistant_agent_kwargs=dict(
- model_type=model_type,
- model_config=assistant_model_config,
+ model=ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=assistant_model_config.__dict__,
+ ),
tools=function_list,
),
user_agent_kwargs=dict(
- model_type=model_type,
- model_config=user_model_config,
+ model=ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=user_model_config.__dict__,
+ ),
),
task_prompt=task_prompt,
with_task_specify=False,
diff --git a/examples/misalignment/single_agent.py b/examples/misalignment/single_agent.py
index 597cc3ed7..de4b2d5d9 100644
--- a/examples/misalignment/single_agent.py
+++ b/examples/misalignment/single_agent.py
@@ -29,7 +29,7 @@ def main(model=None) -> None:
role_name="Assistant",
content=sys_prompt,
)
- agent = ChatAgent(assistant_sys_msg, model_type=model)
+ agent = ChatAgent(assistant_sys_msg, model=model)
agent.reset()
user_msg = BaseMessage.make_user_message(role_name="User", content=prompt)
diff --git a/examples/open_source_models/ollama_model.py b/examples/open_source_models/ollama_model.py
new file mode 100644
index 000000000..7c7b2f4ba
--- /dev/null
+++ b/examples/open_source_models/ollama_model.py
@@ -0,0 +1,72 @@
+# =========== 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 camel.agents import ChatAgent
+from camel.messages import BaseMessage
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType
+
+ollama_model = ModelFactory.create(
+ model_platform=ModelPlatformType.OLLAMA,
+ model_type="camelai-llama3",
+ url="http://localhost:11434/v1",
+ model_config_dict={"temperature": 0.4},
+)
+
+assistant_sys_msg = BaseMessage.make_assistant_message(
+ role_name="Assistant",
+ content="You are a helpful assistant.",
+)
+agent = ChatAgent(assistant_sys_msg, model=ollama_model, token_limit=4096)
+agent.reset()
+
+user_msg = BaseMessage.make_user_message(
+ role_name="User", content="say hi to me"
+)
+assistant_response = agent.step(user_msg)
+print(assistant_response.msg.content)
+
+""" Content in Llama3ModelFile:
+===============================================================================
+FROM llama3
+
+# Set parameters
+
+PARAMETER temperature 0.8
+PARAMETER stop Result
+
+# Sets a custom system message to specify the behavior of the chat assistant
+
+# Leaving it blank for now.
+
+SYSTEM """ """
+===============================================================================
+"""
+
+
+""" Content in .sh file:
+===============================================================================
+#!/bin/zsh
+
+# variables
+model_name="llama3"
+custom_model_name="camel-llama3"
+
+#get the base model
+ollama pull $model_name
+
+#create the model file
+ollama create $custom_model_name -f ./Llama3ModelFile
+===============================================================================
+"""
diff --git a/examples/open_source_models/role_playing_with_open_source_model.py b/examples/open_source_models/role_playing_with_open_source_model.py
index a7f9a3b89..71711a50d 100644
--- a/examples/open_source_models/role_playing_with_open_source_model.py
+++ b/examples/open_source_models/role_playing_with_open_source_model.py
@@ -14,23 +14,35 @@
from colorama import Fore
from camel.configs import ChatGPTConfig, OpenSourceConfig
+from camel.models import ModelFactory
from camel.societies import RolePlaying
-from camel.types import ModelType
+from camel.types import ModelPlatformType, ModelType
from camel.utils import print_text_animated
+# 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"
def main(
- model_type=None, chat_turn_limit=50, model_path=" ", server_url=" "
+ chat_turn_limit=50,
+ model_platform=ModelPlatformType.OPENSOURCE,
+ model_type=ModelType.STUB,
+ model_path="meta-llama/Llama-2-7b-chat-hf",
+ server_url="http://localhost:8000/v1",
) -> None:
task_prompt = "Develop a trading bot for the stock market"
agent_kwargs = {
role: dict(
- model_type=model_type,
- model_config=OpenSourceConfig(
- model_path=model_path,
- server_url=server_url,
- api_params=ChatGPTConfig(temperature=0),
+ model=ModelFactory.create(
+ model_platform=model_platform,
+ model_type=model_type,
+ model_config_dict=OpenSourceConfig(
+ model_path=model_path,
+ server_url=server_url,
+ api_params=ChatGPTConfig(temperature=0),
+ ).__dict__,
),
)
for role in ["assistant", "user", "task-specify"]
@@ -102,12 +114,4 @@ def main(
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",
- )
+ main()
diff --git a/examples/role_description/role_generation.py b/examples/role_description/role_generation.py
index 62cf03dd7..725930c48 100644
--- a/examples/role_description/role_generation.py
+++ b/examples/role_description/role_generation.py
@@ -14,16 +14,12 @@
from colorama import Fore
from camel.agents import RoleAssignmentAgent
-from camel.configs import ChatGPTConfig
-def main(model_type=None, num_roles=3) -> None:
+def main(model=None, num_roles=3) -> None:
task_prompt = "Develop a trading bot for the stock market."
- model_config_description = ChatGPTConfig()
- role_description_agent = RoleAssignmentAgent(
- model_type=model_type, model_config=model_config_description
- )
+ role_description_agent = RoleAssignmentAgent(model=model)
role_description_dict = role_description_agent.run(
task_prompt=task_prompt, num_roles=num_roles
diff --git a/examples/role_description/role_playing_with_role_description.py b/examples/role_description/role_playing_with_role_description.py
index 5775a12fb..e3eb9e749 100644
--- a/examples/role_description/role_playing_with_role_description.py
+++ b/examples/role_description/role_playing_with_role_description.py
@@ -14,7 +14,6 @@
from colorama import Fore
from camel.agents import RoleAssignmentAgent
-from camel.configs import ChatGPTConfig
from camel.societies import RolePlaying
from camel.types import TaskType
from camel.utils import print_text_animated
@@ -24,14 +23,12 @@ AI_USER_ROLE_INDEX = 1
def main(
- model_type_for_role_generation=None, model_type=None, chat_turn_limit=50
+ model_for_role_generation=None, model=None, chat_turn_limit=50
) -> None:
task_prompt = "Develop a trading bot for the stock market."
- model_config_description = ChatGPTConfig()
role_description_agent = RoleAssignmentAgent(
- model_type=model_type_for_role_generation,
- model_config=model_config_description,
+ model=model_for_role_generation,
)
role_description_dict = role_description_agent.run(
@@ -59,10 +56,10 @@ def main(
assistant_role_name=ai_assistant_role,
user_role_name=ai_user_role,
task_prompt=task_prompt,
- model_type=model_type,
+ model=model,
task_type=TaskType.ROLE_DESCRIPTION, # Score for role description
with_task_specify=True,
- task_specify_agent_kwargs=dict(model_type=model_type),
+ task_specify_agent_kwargs=dict(model=model),
extend_sys_msg_meta_dicts=sys_msg_meta_dicts,
)
diff --git a/examples/single_agent.py b/examples/single_agent.py
index 8f348e0ff..5fbeb3236 100644
--- a/examples/single_agent.py
+++ b/examples/single_agent.py
@@ -27,7 +27,7 @@ def main(key: str = 'generate_users', num_roles: int = 50, model=None):
role_name="Assistant",
content="You are a helpful assistant.",
)
- agent = ChatAgent(assistant_sys_msg, model_type=model)
+ agent = ChatAgent(assistant_sys_msg, model=model)
agent.reset()
user_msg = BaseMessage.make_user_message(role_name="User", content=prompt)
diff --git a/examples/summarization/gpt_solution_extraction.py b/examples/summarization/gpt_solution_extraction.py
index 62504ff72..a80e9d5ea 100644
--- a/examples/summarization/gpt_solution_extraction.py
+++ b/examples/summarization/gpt_solution_extraction.py
@@ -24,7 +24,7 @@ import numpy as np
from camel.agents import ChatAgent
from camel.messages import BaseMessage
from camel.prompts import SolutionExtractionPromptTemplateDict
-from camel.types import ModelType, RoleType
+from camel.types import RoleType
parser = argparse.ArgumentParser(
description='Arguments for conversation summarization.'
@@ -135,7 +135,7 @@ def solution_extraction(
)
# We use GPT4 because it has a longer context length
- agent = ChatAgent(assistant_sys_msg, model_type=ModelType.GPT_4)
+ agent = ChatAgent(assistant_sys_msg)
agent.reset()
prompt = "Here is the conversation:" + flattened_conversation
diff --git a/examples/test/test_ai_society_example.py b/examples/test/test_ai_society_example.py
index f36c05682..fe50168a3 100644
--- a/examples/test/test_ai_society_example.py
+++ b/examples/test/test_ai_society_example.py
@@ -16,25 +16,32 @@ from mock import patch
import examples.ai_society.role_playing
import examples.function_call.role_playing_with_functions
import examples.open_source_models.role_playing_with_open_source_model
-from camel.types import ModelType
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType
+
+test_model = ModelFactory.create(
+ model_platform=ModelPlatformType.DEFAULT,
+ model_type=ModelType.STUB,
+ model_config_dict={},
+)
def test_ai_society_role_playing_example():
with patch('time.sleep', return_value=None):
examples.ai_society.role_playing.main(
- ModelType.STUB, chat_turn_limit=2
+ model=test_model, chat_turn_limit=2
)
def test_role_playing_with_function_example():
with patch('time.sleep', return_value=None):
examples.function_call.role_playing_with_functions.main(
- ModelType.STUB, chat_turn_limit=2
+ chat_turn_limit=2
)
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, chat_turn_limit=2
+ chat_turn_limit=2
)
diff --git a/examples/test/test_babyagi_example.py b/examples/test/test_babyagi_example.py
index 15d7d87d9..c5414a730 100644
--- a/examples/test/test_babyagi_example.py
+++ b/examples/test/test_babyagi_example.py
@@ -15,12 +15,17 @@ import pytest
from mock import patch
import examples.ai_society.babyagi_playing
-from camel.types import ModelType
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType
parametrize = pytest.mark.parametrize(
'model',
[
- ModelType.STUB,
+ ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.STUB,
+ model_config_dict={},
+ ),
pytest.param(None, marks=pytest.mark.model_backend),
],
)
@@ -30,5 +35,5 @@ parametrize = pytest.mark.parametrize(
def test_ai_society_babyagi_playing_example(model):
with patch('time.sleep', return_value=None):
examples.ai_society.babyagi_playing.main(
- model_type=model, chat_turn_limit=2
+ model=model, chat_turn_limit=2
)
diff --git a/examples/test/test_code_example.py b/examples/test/test_code_example.py
index 7f325c4e9..888f30d66 100644
--- a/examples/test/test_code_example.py
+++ b/examples/test/test_code_example.py
@@ -14,9 +14,17 @@
from mock import patch
import examples.code.role_playing
-from camel.types import ModelType
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType
def test_code_role_playing_example():
with patch('time.sleep', return_value=None):
- examples.code.role_playing.main(ModelType.STUB, chat_turn_limit=2)
+ examples.code.role_playing.main(
+ ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.STUB,
+ model_config_dict={},
+ ),
+ chat_turn_limit=2,
+ )
diff --git a/examples/test/test_role_description_example.py b/examples/test/test_role_description_example.py
index c0b18eac2..86b9d3b12 100644
--- a/examples/test/test_role_description_example.py
+++ b/examples/test/test_role_description_example.py
@@ -15,16 +15,23 @@ from mock import patch
import examples.role_description.role_generation
import examples.role_description.role_playing_with_role_description
-from camel.types import ModelType
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType
+
+model = ModelFactory.create(
+ ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict={},
+)
def test_role_generation_example():
with patch('time.sleep', return_value=None):
- examples.role_description.role_generation.main(ModelType.GPT_3_5_TURBO)
+ examples.role_description.role_generation.main(model)
def test_role_playing_with_role_description_example():
with patch('time.sleep', return_value=None):
examples.role_description.role_playing_with_role_description.main(
- ModelType.GPT_3_5_TURBO, ModelType.STUB, chat_turn_limit=2
+ model, model, chat_turn_limit=2
)
diff --git a/examples/test/test_single_agent.py b/examples/test/test_single_agent.py
index d9f5d5e45..6b303e8f7 100644
--- a/examples/test/test_single_agent.py
+++ b/examples/test/test_single_agent.py
@@ -18,12 +18,17 @@ import examples.code.task_generation
import examples.evaluation.single_agent
import examples.misalignment.single_agent
import examples.single_agent
-from camel.types import ModelType
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType
parametrize = pytest.mark.parametrize(
'model',
[
- ModelType.STUB,
+ ModelFactory.create(
+ ModelPlatformType.OPENAI,
+ model_type=ModelType.STUB,
+ model_config_dict={},
+ ),
pytest.param(None, marks=pytest.mark.model_backend),
],
)
@@ -39,7 +44,7 @@ def test_misalignment_single_agent(model):
examples.misalignment.single_agent.main(model=model)
[email protected]('model', [ModelType.STUB])
+@parametrize
def test_evaluation_single_agent(model):
examples.evaluation.single_agent.main(model=model)
@@ -49,6 +54,6 @@ def test_code_generate_metadata(model):
examples.code.generate_meta_data.main(model=model)
[email protected]('model', [ModelType.STUB])
+@parametrize
def test_code_task_generation(model):
examples.code.task_generation.main(model=model)
diff --git a/examples/translation/translator.py b/examples/translation/translator.py
index 6d0ae7d18..e3d205f5a 100644
--- a/examples/translation/translator.py
+++ b/examples/translation/translator.py
@@ -23,7 +23,8 @@ from camel.agents import ChatAgent
from camel.configs import ChatGPTConfig
from camel.generators import SystemMessageGenerator
from camel.messages import BaseMessage
-from camel.types import ModelType, RoleType, TaskType
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType, RoleType, TaskType
warnings.filterwarnings("ignore")
@@ -117,12 +118,17 @@ def translate_content(
else:
model_config = ChatGPTConfig(stream=True)
- assistant_agent = ChatAgent(
- system_message=assistant_sys_msg,
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OpenAI,
model_type=ModelType.GPT_3_5_TURBO,
model_config=model_config,
)
+ assistant_agent = ChatAgent(
+ system_message=assistant_sys_msg,
+ model=model,
+ )
+
user_msg = BaseMessage.make_user_message(
role_name="Language Translator", content=msg_i_content
)
diff --git a/test/agents/test_babyagi_playing.py b/test/agents/test_babyagi_playing.py
index a5e2f2773..534bf5150 100644
--- a/test/agents/test_babyagi_playing.py
+++ b/test/agents/test_babyagi_playing.py
@@ -15,29 +15,33 @@ import pytest
from camel.agents import ChatAgent, TaskCreationAgent, TaskPrioritizationAgent
from camel.messages import BaseMessage
+from camel.models import ModelFactory
from camel.societies import BabyAGI
-from camel.types import ModelType, RoleType, TaskType
+from camel.types import ModelPlatformType, ModelType, RoleType, TaskType
parametrize = pytest.mark.parametrize(
'model',
[
- None,
- pytest.param(ModelType.GPT_3_5_TURBO, marks=pytest.mark.model_backend),
- pytest.param(ModelType.GPT_4, marks=pytest.mark.model_backend),
+ ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.STUB,
+ model_config_dict={},
+ ),
+ pytest.param(None, marks=pytest.mark.model_backend),
],
)
@parametrize
-def test_babyagi_playing_init(model: ModelType):
+def test_babyagi_playing_init(model):
task_prompt = "Develop a trading bot for the stock market"
babyagi_playing = BabyAGI(
assistant_role_name="Python Programmer",
- assistant_agent_kwargs=dict(model_type=model),
+ assistant_agent_kwargs=dict(model=model),
user_role_name="Stock Trader",
task_prompt=task_prompt,
- task_specify_agent_kwargs=dict(model_type=model),
+ task_specify_agent_kwargs=dict(model=model),
message_window_size=5,
)
@@ -58,15 +62,15 @@ def test_babyagi_playing_init(model: ModelType):
@parametrize
-def test_babyagi_playing_step(model: ModelType):
+def test_babyagi_playing_step(model):
task_prompt = "Develop a trading bot for the stock market"
babyagi_playing = BabyAGI(
assistant_role_name="Python Programmer",
- assistant_agent_kwargs=dict(model_type=model),
+ assistant_agent_kwargs=dict(model=model),
user_role_name="Stock Trader",
task_prompt=task_prompt,
- task_specify_agent_kwargs=dict(model_type=model),
+ task_specify_agent_kwargs=dict(model=model),
message_window_size=5,
)
diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.py
index 602ce771b..3c4c5e3d9 100644
--- a/test/agents/test_chat_agent.py
+++ b/test/agents/test_chat_agent.py
@@ -30,9 +30,11 @@ from camel.functions.openai_function import OpenAIFunction
from camel.generators import SystemMessageGenerator
from camel.memories import MemoryRecord
from camel.messages import BaseMessage
+from camel.models import ModelFactory
from camel.terminators import ResponseWordsTerminator
from camel.types import (
ChatCompletion,
+ ModelPlatformType,
ModelType,
OpenAIBackendRole,
RoleType,
@@ -42,28 +44,29 @@ from camel.types import (
parametrize = pytest.mark.parametrize(
'model',
[
- ModelType.STUB,
- pytest.param(ModelType.GPT_3_5_TURBO, marks=pytest.mark.model_backend),
- pytest.param(ModelType.GPT_4, marks=pytest.mark.model_backend),
+ ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=ChatGPTConfig().__dict__,
+ ),
+ pytest.param(None, marks=pytest.mark.model_backend),
],
)
@parametrize
-def test_chat_agent(model: ModelType):
- model_config = ChatGPTConfig()
+def test_chat_agent(model):
+ model = model
system_msg = SystemMessageGenerator(
task_type=TaskType.AI_SOCIETY
).from_dict(
dict(assistant_role="doctor"),
role_tuple=("doctor", RoleType.ASSISTANT),
)
- assistant = ChatAgent(
- system_msg, model_type=model, model_config=model_config
- )
+ assistant = ChatAgent(system_msg, model=model)
assert str(assistant) == (
- "ChatAgent(doctor, " f"RoleType.ASSISTANT, {model!s})"
+ "ChatAgent(doctor, " f"RoleType.ASSISTANT, {ModelType.GPT_3_5_TURBO})"
)
assistant.reset()
@@ -121,7 +124,6 @@ def test_chat_agent_messages_window():
)
assistant = ChatAgent(
system_message=system_msg,
- model_type=ModelType.GPT_3_5_TURBO,
message_window_size=2,
)
@@ -155,7 +157,6 @@ def test_chat_agent_step_exceed_token_number():
)
assistant = ChatAgent(
system_message=system_msg,
- model_type=ModelType.GPT_3_5_TURBO,
token_limit=1,
)
@@ -175,13 +176,18 @@ def test_chat_agent_step_exceed_token_number():
@pytest.mark.parametrize('n', [1, 2, 3])
def test_chat_agent_multiple_return_messages(n):
model_config = ChatGPTConfig(temperature=1.4, n=n)
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=model_config.__dict__,
+ )
system_msg = BaseMessage(
"Assistant",
RoleType.ASSISTANT,
meta_dict=None,
content="You are a helpful assistant.",
)
- assistant = ChatAgent(system_msg, model_config=model_config)
+ assistant = ChatAgent(system_msg, model=model)
assistant.reset()
user_msg = BaseMessage(
role_name="User",
@@ -198,6 +204,11 @@ def test_chat_agent_multiple_return_messages(n):
@pytest.mark.parametrize('n', [2])
def test_chat_agent_multiple_return_message_error(n):
model_config = ChatGPTConfig(temperature=1.4, n=n)
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=model_config.__dict__,
+ )
system_msg = BaseMessage(
"Assistant",
RoleType.ASSISTANT,
@@ -205,7 +216,7 @@ def test_chat_agent_multiple_return_message_error(n):
content="You are a helpful assistant.",
)
- assistant = ChatAgent(system_msg, model_config=model_config)
+ assistant = ChatAgent(system_msg, model=model)
assistant.reset()
user_msg = BaseMessage(
@@ -241,7 +252,12 @@ def test_chat_agent_stream_output():
)
stream_model_config = ChatGPTConfig(temperature=0, n=2, stream=True)
- stream_assistant = ChatAgent(system_msg, model_config=stream_model_config)
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=stream_model_config.__dict__,
+ )
+ stream_assistant = ChatAgent(system_msg, model=model)
stream_assistant.reset()
stream_assistant_response = stream_assistant.step(user_msg)
@@ -265,9 +281,7 @@ def test_set_output_language():
meta_dict=None,
content="You are a help assistant.",
)
- agent = ChatAgent(
- system_message=system_message, model_type=ModelType.GPT_3_5_TURBO
- )
+ agent = ChatAgent(system_message=system_message)
assert agent.output_language is None
# Set the output language to "Arabic"
@@ -296,9 +310,7 @@ def test_set_multiple_output_language():
meta_dict=None,
content="You are a help assistant.",
)
- agent = ChatAgent(
- system_message=system_message, model_type=ModelType.GPT_3_5_TURBO
- )
+ agent = ChatAgent(system_message=system_message)
# Verify that the length of the system message is kept constant even when
# multiple set_output_language operations are called
@@ -323,9 +335,7 @@ def test_token_exceed_return():
meta_dict=None,
content="You are a help assistant.",
)
- agent = ChatAgent(
- system_message=system_message, model_type=ModelType.GPT_3_5_TURBO
- )
+ agent = ChatAgent(system_message=system_message)
expect_info = {
"id": None,
@@ -350,15 +360,15 @@ def test_function_enabled():
content="You are a help assistant.",
)
model_config = ChatGPTConfig(tools=[*MATH_FUNCS])
- agent_no_func = ChatAgent(
- system_message=system_message,
- model_config=model_config,
- model_type=ModelType.GPT_4,
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=model_config.__dict__,
)
+ agent_no_func = ChatAgent(system_message=system_message)
agent_with_funcs = ChatAgent(
system_message=system_message,
- model_config=model_config,
- model_type=ModelType.GPT_4,
+ model=model,
tools=MATH_FUNCS,
)
@@ -375,10 +385,14 @@ def test_tool_calling_sync():
content="You are a help assistant.",
)
model_config = ChatGPTConfig(tools=[*MATH_FUNCS])
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=model_config.__dict__,
+ )
agent = ChatAgent(
system_message=system_message,
- model_config=model_config,
- model_type=ModelType.GPT_4O,
+ model=model,
tools=MATH_FUNCS,
)
@@ -428,14 +442,17 @@ async def test_tool_calling_async():
await asyncio.sleep(second)
return second
- model_config = ChatGPTConfig(
- temperature=0,
- tools=[OpenAIFunction(async_sleep)],
+ model_config = ChatGPTConfig(tools=[OpenAIFunction(async_sleep)])
+
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=model_config.__dict__,
)
+
agent = ChatAgent(
system_message=system_message,
- model_config=model_config,
- model_type=ModelType.GPT_4O,
+ model=model,
tools=[OpenAIFunction(async_sleep)],
)
@@ -470,11 +487,8 @@ def test_response_words_termination():
content="You are a help assistant.",
)
response_terminator = ResponseWordsTerminator(words_dict=dict(goodbye=1))
- model_config = ChatGPTConfig(temperature=0, n=2)
agent = ChatAgent(
system_message=system_message,
- model_type=ModelType.GPT_3_5_TURBO,
- model_config=model_config,
response_terminators=[response_terminator],
)
user_msg = BaseMessage(
@@ -498,10 +512,14 @@ def test_chat_agent_vision():
content="You are a help assistant.",
)
model_config = ChatGPTConfig(temperature=0, max_tokens=200, stop="")
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O,
+ model_config_dict=model_config.__dict__,
+ )
agent = ChatAgent(
system_message=system_message,
- model_type=ModelType.GPT_4_TURBO,
- model_config=model_config,
+ model=model,
)
# Create an all blue PNG image:
diff --git a/test/agents/test_deductive_reasoner_agent.py b/test/agents/test_deductive_reasoner_agent.py
index ef53daaf2..57f84e82a 100644
--- a/test/agents/test_deductive_reasoner_agent.py
+++ b/test/agents/test_deductive_reasoner_agent.py
@@ -15,7 +15,6 @@ from mock import patch
from camel.agents import ChatAgent
from camel.agents.deductive_reasoner_agent import DeductiveReasonerAgent
-from camel.configs import ChatGPTConfig
from camel.messages import BaseMessage
from camel.responses import ChatAgentResponse
from camel.types import RoleType
@@ -38,13 +37,9 @@ def test_deductive_reasoner_agent(mock_step):
starting_state = "I was walking down the street in New York with a Anna."
target_state = "I remind Anna to pay attention to personal safety."
- model_config_description = ChatGPTConfig()
# Construct deductive reasoner agent
- model_type = None
- deductive_reasoner_agent = DeductiveReasonerAgent(
- model_type=model_type, model_config=model_config_description
- )
+ deductive_reasoner_agent = DeductiveReasonerAgent()
# Generate the conditions and quality dictionary based on the mock step
# function
diff --git a/test/agents/test_role_assignment_agent.py b/test/agents/test_role_assignment_agent.py
index 594ee2d6a..ab23daebe 100644
--- a/test/agents/test_role_assignment_agent.py
+++ b/test/agents/test_role_assignment_agent.py
@@ -15,16 +15,14 @@ import pytest
from mock import patch
from camel.agents import ChatAgent, RoleAssignmentAgent
-from camel.configs import ChatGPTConfig
from camel.messages import BaseMessage
from camel.responses import ChatAgentResponse
-from camel.types import ModelType, RoleType
+from camel.types import RoleType
@patch.object(ChatAgent, 'step')
[email protected]("model_type", [None, ModelType.GPT_3_5_TURBO])
@pytest.mark.parametrize("num_roles", [1, 2, 3])
-def test_role_assignment_agent(mock_step, model_type, num_roles):
+def test_role_assignment_agent(mock_step, num_roles):
mock_content = generate_mock_content(num_roles)
mock_msg = BaseMessage(
role_name="Role Assigner",
@@ -39,12 +37,9 @@ def test_role_assignment_agent(mock_step, model_type, num_roles):
)
task_prompt = "Develop a trading bot for the stock market."
- model_config_description = ChatGPTConfig()
# Construct role assignment agent
- role_description_agent = RoleAssignmentAgent(
- model_type=model_type, model_config=model_config_description
- )
+ role_description_agent = RoleAssignmentAgent()
# Generate the role description dictionary based on the mock step function
role_description_dict = role_description_agent.run(task_prompt, num_roles)
diff --git a/test/agents/test_role_playing.py b/test/agents/test_role_playing.py
index a645a49cf..bccbdca72 100644
--- a/test/agents/test_role_playing.py
+++ b/test/agents/test_role_playing.py
@@ -18,28 +18,33 @@ from camel.configs import ChatGPTConfig
from camel.functions import MATH_FUNCS
from camel.human import Human
from camel.messages import BaseMessage
+from camel.models import ModelFactory
from camel.societies import RolePlaying
-from camel.types import ModelType, RoleType, TaskType
+from camel.types import ModelPlatformType, ModelType, RoleType, TaskType
+
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O,
+ model_config_dict=ChatGPTConfig().__dict__,
+)
[email protected]("model_type", [None, ModelType.GPT_4])
[email protected]("model", [None, model])
@pytest.mark.parametrize("critic_role_name", ["human", "critic agent"])
@pytest.mark.parametrize("with_critic_in_the_loop", [True, False])
-def test_role_playing_init(
- model_type, critic_role_name, with_critic_in_the_loop
-):
+def test_role_playing_init(model, critic_role_name, with_critic_in_the_loop):
role_playing = RolePlaying(
assistant_role_name="assistant",
- assistant_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO),
+ assistant_agent_kwargs=dict(model=model),
user_role_name="user",
- user_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO),
- model_type=model_type,
+ user_agent_kwargs=dict(model=model),
+ model=model,
critic_role_name=critic_role_name,
task_prompt="Perform the task",
with_task_specify=False,
- task_specify_agent_kwargs=dict(model_type=ModelType.GPT_4),
+ task_specify_agent_kwargs=dict(model=model),
with_task_planner=False,
- task_planner_agent_kwargs=dict(model_type=ModelType.GPT_4),
+ task_planner_agent_kwargs=dict(model=model),
with_critic_in_the_loop=with_critic_in_the_loop,
task_type=TaskType.AI_SOCIETY,
)
@@ -62,12 +67,14 @@ def test_role_playing_init(
assert isinstance(assistant_agent, ChatAgent)
assert isinstance(user_agent, ChatAgent)
- if model_type is None:
- assert assistant_agent.model_type == ModelType.GPT_3_5_TURBO
- assert user_agent.model_type == ModelType.GPT_3_5_TURBO
+ if model is None:
+ assert (
+ assistant_agent.model_backend.model_type == ModelType.GPT_3_5_TURBO
+ )
+ assert user_agent.model_backend.model_type == ModelType.GPT_3_5_TURBO
else:
- assert assistant_agent.model_type == ModelType.GPT_4
- assert user_agent.model_type == ModelType.GPT_4
+ assert assistant_agent.model_backend.model_type == ModelType.GPT_4O
+ assert user_agent.model_backend.model_type == ModelType.GPT_4O
if not with_critic_in_the_loop:
assert critic is None
@@ -78,10 +85,12 @@ def test_role_playing_init(
else:
assert isinstance(critic, CriticAgent)
assert role_playing.critic_sys_msg is not None
- if model_type is None:
- assert critic.model_type == ModelType.GPT_3_5_TURBO
+ if model is None:
+ assert (
+ critic.model_backend.model_type == ModelType.GPT_3_5_TURBO
+ )
else:
- assert critic.model_type == ModelType.GPT_4
+ assert critic.model_backend.model_type == ModelType.GPT_4O
@pytest.mark.model_backend
@@ -102,11 +111,11 @@ def test_role_playing_step(
):
role_playing = RolePlaying(
assistant_role_name="AI Assistant",
- assistant_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO),
+ assistant_agent_kwargs=dict(model=model),
user_role_name="AI User",
- user_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO),
+ user_agent_kwargs=dict(model=model),
task_prompt="Perform the task",
- task_specify_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO),
+ task_specify_agent_kwargs=dict(model=model),
task_type=task_type,
extend_sys_msg_meta_dicts=extend_sys_msg_meta_dicts,
extend_task_specify_meta_dict=extend_task_specify_meta_dict,
@@ -132,18 +141,22 @@ def test_role_playing_step(
def test_role_playing_with_function():
tools = [*MATH_FUNCS]
assistant_model_config = ChatGPTConfig(tools=tools)
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_3_5_TURBO,
+ model_config_dict=assistant_model_config.__dict__,
+ )
role_playing = RolePlaying(
assistant_role_name="AI Assistant",
assistant_agent_kwargs=dict(
- model_type=ModelType.GPT_3_5_TURBO,
- model_config=assistant_model_config,
+ model=model,
tools=tools,
),
user_role_name="AI User",
- user_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO),
+ user_agent_kwargs=dict(model=model),
task_prompt="Perform the task",
- task_specify_agent_kwargs=dict(model_type=ModelType.GPT_3_5_TURBO),
+ task_specify_agent_kwargs=dict(model=model),
task_type=TaskType.AI_SOCIETY,
)
@@ -158,16 +171,16 @@ def test_role_playing_with_function():
assert isinstance(response.info, dict)
-def test_role_playing_role_sequence(model_type=None):
+def test_role_playing_role_sequence(model=None):
task_prompt = "Develop a trading bot for the stock market"
role_playing = RolePlaying(
assistant_role_name="Python Programmer",
- assistant_agent_kwargs=dict(model_type=model_type),
+ assistant_agent_kwargs=dict(model=model),
user_role_name="Stock Trader",
- user_agent_kwargs=dict(model_type=model_type),
+ user_agent_kwargs=dict(model=model),
task_prompt=task_prompt,
with_task_specify=True,
- task_specify_agent_kwargs=dict(model_type=model_type),
+ task_specify_agent_kwargs=dict(model=model),
)
assistant_role_sequence = []
user_role_sequence = []
diff --git a/test/agents/test_task_agent.py b/test/agents/test_task_agent.py
index 167968c56..a82f77cd7 100644
--- a/test/agents/test_task_agent.py
+++ b/test/agents/test_task_agent.py
@@ -11,8 +11,6 @@
# 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 Optional
-
import pytest
from camel.agents import (
@@ -21,25 +19,27 @@ from camel.agents import (
TaskPrioritizationAgent,
TaskSpecifyAgent,
)
-from camel.configs import ChatGPTConfig
-from camel.types import ModelType, TaskType
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType, TaskType
parametrize = pytest.mark.parametrize(
'model',
[
- ModelType.STUB,
+ ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.STUB,
+ model_config_dict={},
+ ),
pytest.param(None, marks=pytest.mark.model_backend),
],
)
@parametrize
-def test_task_specify_ai_society_agent(model: Optional[ModelType]):
+def test_task_specify_ai_society_agent(model):
original_task_prompt = "Improving stage presence and performance skills"
print(f"Original task prompt:\n{original_task_prompt}\n")
- task_specify_agent = TaskSpecifyAgent(
- model_config=ChatGPTConfig(temperature=1.0), model_type=model
- )
+ task_specify_agent = TaskSpecifyAgent(model=model)
specified_task_prompt = task_specify_agent.run(
original_task_prompt,
meta_dict=dict(assistant_role="Musician", user_role="Student"),
@@ -49,14 +49,10 @@ def test_task_specify_ai_society_agent(model: Optional[ModelType]):
@parametrize
-def test_task_specify_code_agent(model: Optional[ModelType]):
+def test_task_specify_code_agent(model):
original_task_prompt = "Modeling molecular dynamics"
print(f"Original task prompt:\n{original_task_prompt}\n")
- task_specify_agent = TaskSpecifyAgent(
- task_type=TaskType.CODE,
- model_config=ChatGPTConfig(temperature=1.0),
- model_type=model,
- )
+ task_specify_agent = TaskSpecifyAgent(model=model, task_type=TaskType.CODE)
specified_task_prompt = task_specify_agent.run(
original_task_prompt,
meta_dict=dict(domain="Chemistry", language="Python"),
@@ -66,34 +62,30 @@ def test_task_specify_code_agent(model: Optional[ModelType]):
@parametrize
-def test_task_planner_agent(model: Optional[ModelType]):
+def test_task_planner_agent(model):
original_task_prompt = "Modeling molecular dynamics"
print(f"Original task prompt:\n{original_task_prompt}\n")
task_specify_agent = TaskSpecifyAgent(
+ model=model,
task_type=TaskType.CODE,
- model_config=ChatGPTConfig(temperature=1.0),
- model_type=model,
)
specified_task_prompt = task_specify_agent.run(
original_task_prompt,
meta_dict=dict(domain="Chemistry", language="Python"),
)
print(f"Specified task prompt:\n{specified_task_prompt}\n")
- task_planner_agent = TaskPlannerAgent(
- model_config=ChatGPTConfig(temperature=1.0), model_type=model
- )
+ task_planner_agent = TaskPlannerAgent()
planned_task_prompt = task_planner_agent.run(specified_task_prompt)
print(f"Planned task prompt:\n{planned_task_prompt}\n")
@parametrize
-def test_task_creation_agent(model: Optional[ModelType]):
+def test_task_creation_agent(model):
original_task_prompt = "Modeling molecular dynamics"
task_creation_agent = TaskCreationAgent(
+ model=model,
role_name="PhD in molecular biology",
objective=original_task_prompt,
- model_type=model,
- model_config=ChatGPTConfig(temperature=1.0),
)
task_list = ["Study the computational technology for dynamics modeling"]
planned_task = task_creation_agent.run(
@@ -104,7 +96,7 @@ def test_task_creation_agent(model: Optional[ModelType]):
@parametrize
-def test_task_prioritization_agent(model: Optional[ModelType]):
+def test_task_prioritization_agent(model):
original_task_prompt = (
"A high school student wants to " "prove the Riemann hypothesis"
)
@@ -120,9 +112,8 @@ def test_task_prioritization_agent(model: Optional[ModelType]):
]
task_prioritization_agent = TaskPrioritizationAgent(
- model_config=ChatGPTConfig(temperature=1.0),
- model_type=model,
objective=original_task_prompt,
+ model=model,
)
prioritized_task = task_prioritization_agent.run(task_list=task_list)
diff --git a/test/functions/tempory_storage/.lock b/test/functions/tempory_storage/.lock
deleted file mode 100644
index a4b31f429..000000000
--- a/test/functions/tempory_storage/.lock
+++ /dev/null
@@ -1 +0,0 @@
-tmp lock file
\ No newline at end of file
diff --git a/test/functions/tempory_storage/collection/collection/storage.sqlite b/test/functions/tempory_storage/collection/collection/storage.sqlite
deleted file mode 100644
index fc555fcdb..000000000
Binary files a/test/functions/tempory_storage/collection/collection/storage.sqlite and /dev/null differ
diff --git a/test/functions/tempory_storage/collection/www_camel_ai_org/storage.sqlite b/test/functions/tempory_storage/collection/www_camel_ai_org/storage.sqlite
deleted file mode 100644
index fc555fcdb..000000000
Binary files a/test/functions/tempory_storage/collection/www_camel_ai_org/storage.sqlite and /dev/null differ
diff --git a/test/models/test_model_factory.py b/test/models/test_model_factory.py
index 76186aaa8..0cd2d2549 100644
--- a/test/models/test_model_factory.py
+++ b/test/models/test_model_factory.py
@@ -15,22 +15,24 @@ import pytest
from camel.configs import ChatGPTConfig
from camel.models import ModelFactory
-from camel.types import ModelType
+from camel.types import ModelPlatformType, ModelType
parametrize = pytest.mark.parametrize(
- 'model',
+ 'model_platform, model_type',
[
- pytest.param(ModelType.GPT_3_5_TURBO, marks=pytest.mark.model_backend),
- pytest.param(ModelType.GPT_4_TURBO, marks=pytest.mark.model_backend),
- ModelType.STUB,
+ (ModelPlatformType.OPENAI, ModelType.GPT_3_5_TURBO),
+ (ModelPlatformType.OPENAI, ModelType.GPT_4_TURBO),
+ (ModelPlatformType.OPENSOURCE, ModelType.STUB),
],
)
@parametrize
-def test_model_factory(model):
+def test_model_factory(model_platform, model_type):
model_config_dict = ChatGPTConfig().__dict__
- model_inst = ModelFactory.create(model, model_config_dict)
+ model_inst = ModelFactory.create(
+ model_platform, model_type, model_config_dict
+ )
messages = [
{
"role": "system",