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

feat: Add CometAPI support with new model and configuration classes (#3169)

TensorNulld4fa167d7e02
diff --git a/.github/workflows/build_package.yml b/.github/workflows/build_package.yml
index 48fd5a9f0..98fc15886 100644
--- a/.github/workflows/build_package.yml
+++ b/.github/workflows/build_package.yml
@@ -142,6 +142,7 @@ jobs:
BOHRIUM_API_KEY: "${{ secrets.BOHRIUM_API_KEY }}"
CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"
+ COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"
run: |
source test_venv/bin/activate
pytest --fast-test-mode -m "not heavy_dependency" \
diff --git a/.github/workflows/pytest_package.yml b/.github/workflows/pytest_package.yml
index 2a3c3ba6b..fc86e180b 100644
--- a/.github/workflows/pytest_package.yml
+++ b/.github/workflows/pytest_package.yml
@@ -81,6 +81,7 @@ jobs:
BOHRIUM_API_KEY: "${{ secrets.BOHRIUM_API_KEY }}"
CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"
+ COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"
run: |
source .venv/bin/activate
uv pip install -e ".[all, dev, docs]"
@@ -167,6 +168,7 @@ jobs:
CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"
AMD_API_KEY: "${{ secrets.AMD_API_KEY }}"
+ COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"
run: |
source .venv/bin/activate
uv pip install -e ".[all, dev, docs]"
@@ -251,6 +253,7 @@ jobs:
CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"
AMD_API_KEY: "${{ secrets.AMD_API_KEY }}"
+ COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"
run: |
source .venv/bin/activate
uv pip install -e ".[all, dev, docs]"
diff --git a/camel/configs/__init__.py b/camel/configs/__init__.py
index f89cb4751..d797efedc 100644
--- a/camel/configs/__init__.py
+++ b/camel/configs/__init__.py
@@ -17,6 +17,7 @@ from .anthropic_config import ANTHROPIC_API_PARAMS, AnthropicConfig
from .base_config import BaseConfig
from .bedrock_config import BEDROCK_API_PARAMS, BedrockConfig
from .cohere_config import COHERE_API_PARAMS, CohereConfig
+from .cometapi_config import COMETAPI_API_PARAMS, CometAPIConfig
from .crynux_config import CRYNUX_API_PARAMS, CrynuxConfig
from .deepseek_config import DEEPSEEK_API_PARAMS, DeepSeekConfig
from .gemini_config import Gemini_API_PARAMS, GeminiConfig
@@ -90,6 +91,8 @@ __all__ = [
'TOGETHERAI_API_PARAMS',
'CohereConfig',
'COHERE_API_PARAMS',
+ 'CometAPIConfig',
+ 'COMETAPI_API_PARAMS',
'YiConfig',
'YI_API_PARAMS',
'QwenConfig',
diff --git a/camel/configs/cometapi_config.py b/camel/configs/cometapi_config.py
new file mode 100644
index 000000000..4b9b8eb34
--- /dev/null
+++ b/camel/configs/cometapi_config.py
@@ -0,0 +1,104 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+from __future__ import annotations
+
+from typing import Optional, Sequence, Union
+
+from camel.configs.base_config import BaseConfig
+
+
+class CometAPIConfig(BaseConfig):
+ r"""Defines the parameters for generating chat completions using CometAPI's
+ OpenAI-compatible interface.
+
+ Reference: https://api.cometapi.com/v1/
+
+ Args:
+ temperature (float, optional): Sampling temperature to use, between
+ :obj:`0` and :obj:`2`. Higher values make the output more random,
+ while lower values make it more focused and deterministic.
+ (default: :obj:`None`)
+ top_p (float, optional): An alternative to sampling with temperature,
+ called nucleus sampling, where the model considers the results of
+ the tokens with top_p probability mass. So :obj:`0.1` means only
+ the tokens comprising the top 10% probability mass are considered.
+ (default: :obj:`None`)
+ n (int, optional): How many chat completion choices to generate for
+ each input message. (default: :obj:`None`)
+ response_format (object, optional): An object specifying the format
+ that the model must output. Compatible with GPT-4 Turbo and all
+ GPT-3.5 Turbo models newer than gpt-3.5-turbo-1106. Setting to
+ {"type": "json_object"} enables JSON mode, which guarantees the
+ message the model generates is valid JSON. Important: when using
+ JSON mode, you must also instruct the model to produce JSON
+ yourself via a system or user message. Without this, the model
+ may generate an unending stream of whitespace until the generation
+ reaches the token limit, resulting in a long-running and seemingly
+ "stuck" request. Also note that the message content may be
+ partially cut off if finish_reason="length", which indicates the
+ generation exceeded max_tokens or the conversation exceeded the
+ max context length.
+ stream (bool, optional): If True, partial message deltas will be sent
+ as data-only server-sent events as they become available.
+ (default: :obj:`None`)
+ stop (str or list, optional): Up to :obj:`4` sequences where the API
+ will stop generating further tokens. (default: :obj:`None`)
+ max_tokens (int, optional): The maximum number of tokens to generate
+ in the chat completion. The total length of input tokens and
+ generated tokens is limited by the model's context length.
+ (default: :obj:`None`)
+ presence_penalty (float, optional): Number between :obj:`-2.0` and
+ :obj:`2.0`. Positive values penalize new tokens based on whether
+ they appear in the text so far, increasing the model's likelihood
+ to talk about new topics. See more information about frequency and
+ presence penalties. (default: :obj:`None`)
+ frequency_penalty (float, optional): Number between :obj:`-2.0` and
+ :obj:`2.0`. Positive values penalize new tokens based on their
+ existing frequency in the text so far, decreasing the model's
+ likelihood to repeat the same line verbatim. See more information
+ about frequency and presence penalties. (default: :obj:`None`)
+ user (str, optional): A unique identifier representing your end-user,
+ which can help CometAPI to monitor and detect abuse.
+ (default: :obj:`None`)
+ tools (list[FunctionTool], optional): A list of tools the model may
+ call. Currently, only functions are supported as a tool. Use this
+ to provide a list of functions the model may generate JSON inputs
+ for. A max of 128 functions are supported.
+ tool_choice (Union[dict[str, str], str], optional): Controls which (if
+ any) tool is called by the model. :obj:`"none"` means the model
+ will not call any tool and instead generates a message.
+ :obj:`"auto"` means the model can pick between generating a
+ message or calling one or more tools. :obj:`"required"` means the
+ model must call one or more tools. Specifying a particular tool
+ via {"type": "function", "function": {"name": "my_function"}}
+ forces the model to call that tool. :obj:`"none"` is the default
+ when no tools are present. :obj:`"auto"` is the default if tools
+ are present.
+ """
+
+ temperature: Optional[float] = None
+ top_p: Optional[float] = None
+ n: Optional[int] = None
+ stream: Optional[bool] = None
+ stop: Optional[Union[str, Sequence[str]]] = None
+ max_tokens: Optional[int] = None
+ presence_penalty: Optional[float] = None
+ response_format: Optional[dict] = None
+ frequency_penalty: Optional[float] = None
+ user: Optional[str] = None
+ tools: Optional[list] = None
+ tool_choice: Optional[Union[dict[str, str], str]] = None
+
+
+COMETAPI_API_PARAMS = {param for param in CometAPIConfig.model_fields.keys()}
diff --git a/camel/models/__init__.py b/camel/models/__init__.py
index 229c571ca..b34a201e0 100644
--- a/camel/models/__init__.py
+++ b/camel/models/__init__.py
@@ -19,6 +19,7 @@ from .azure_openai_model import AzureOpenAIModel
from .base_audio_model import BaseAudioModel
from .base_model import BaseModelBackend
from .cohere_model import CohereModel
+from .cometapi_model import CometAPIModel
from .crynux_model import CrynuxModel
from .deepseek_model import DeepSeekModel
from .fish_audio_model import FishAudioModel
@@ -69,6 +70,7 @@ __all__ = [
'StubModel',
'ZhipuAIModel',
'CohereModel',
+ 'CometAPIModel',
'ModelFactory',
'ModelManager',
'LiteLLMModel',
diff --git a/camel/models/cometapi_model.py b/camel/models/cometapi_model.py
new file mode 100644
index 000000000..f02360cd0
--- /dev/null
+++ b/camel/models/cometapi_model.py
@@ -0,0 +1,83 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+import os
+from typing import Any, Dict, Optional, Union
+
+from camel.configs import CometAPIConfig
+from camel.models.openai_compatible_model import OpenAICompatibleModel
+from camel.types import ModelType
+from camel.utils import (
+ BaseTokenCounter,
+ api_keys_required,
+)
+
+
+class CometAPIModel(OpenAICompatibleModel):
+ r"""LLM API served by CometAPI in a unified OpenAICompatibleModel
+ interface.
+
+ Args:
+ model_type (Union[ModelType, str]): Model for which a backend is
+ created.
+ model_config_dict (Optional[Dict[str, Any]], optional): A dictionary
+ that will be fed into:obj:`openai.ChatCompletion.create()`.
+ If:obj:`None`, :obj:`CometAPIConfig().as_dict()` will be used.
+ (default: :obj:`None`)
+ api_key (Optional[str], optional): The API key for authenticating
+ with the CometAPI service. (default: :obj:`None`).
+ url (Optional[str], optional): The url to the CometAPI service.
+ (default: :obj:`None`)
+ token_counter (Optional[BaseTokenCounter], optional): Token counter to
+ use for the model. If not provided, :obj:`OpenAITokenCounter(
+ ModelType.GPT_4O_MINI)` will be used.
+ (default: :obj:`None`)
+ timeout (Optional[float], optional): The timeout value in seconds for
+ API calls. If not provided, will fall back to the MODEL_TIMEOUT
+ environment variable or default to 180 seconds.
+ (default: :obj:`None`)
+ max_retries (int, optional): Maximum number of retries for API calls.
+ (default: :obj:`3`)
+ **kwargs (Any): Additional arguments to pass to the client
+ initialization.
+ """
+
+ @api_keys_required([("api_key", "COMETAPI_KEY")])
+ def __init__(
+ self,
+ model_type: Union[ModelType, str],
+ model_config_dict: Optional[Dict[str, Any]] = None,
+ api_key: Optional[str] = None,
+ url: Optional[str] = None,
+ token_counter: Optional[BaseTokenCounter] = None,
+ timeout: Optional[float] = None,
+ max_retries: int = 3,
+ **kwargs: Any,
+ ) -> None:
+ if model_config_dict is None:
+ model_config_dict = CometAPIConfig().as_dict()
+ api_key = api_key or os.environ.get("COMETAPI_KEY")
+ url = url or os.environ.get(
+ "COMETAPI_API_BASE_URL", "https://api.cometapi.com/v1"
+ )
+ timeout = timeout or float(os.environ.get("MODEL_TIMEOUT", 180))
+ super().__init__(
+ model_type=model_type,
+ model_config_dict=model_config_dict,
+ api_key=api_key,
+ url=url,
+ token_counter=token_counter,
+ timeout=timeout,
+ max_retries=max_retries,
+ **kwargs,
+ )
diff --git a/camel/models/model_factory.py b/camel/models/model_factory.py
index 387f9ea69..6155ca82e 100644
--- a/camel/models/model_factory.py
+++ b/camel/models/model_factory.py
@@ -22,6 +22,7 @@ from camel.models.aws_bedrock_model import AWSBedrockModel
from camel.models.azure_openai_model import AzureOpenAIModel
from camel.models.base_model import BaseModelBackend
from camel.models.cohere_model import CohereModel
+from camel.models.cometapi_model import CometAPIModel
from camel.models.crynux_model import CrynuxModel
from camel.models.deepseek_model import DeepSeekModel
from camel.models.gemini_model import GeminiModel
@@ -86,6 +87,7 @@ class ModelFactory:
ModelPlatformType.AZURE: AzureOpenAIModel,
ModelPlatformType.ANTHROPIC: AnthropicModel,
ModelPlatformType.GROQ: GroqModel,
+ ModelPlatformType.COMETAPI: CometAPIModel,
ModelPlatformType.NEBIUS: NebiusModel,
ModelPlatformType.LMSTUDIO: LMStudioModel,
ModelPlatformType.OPENROUTER: OpenRouterModel,
diff --git a/camel/types/enums.py b/camel/types/enums.py
index 50ed4612f..a3967618b 100644
--- a/camel/types/enums.py
+++ b/camel/types/enums.py
@@ -98,6 +98,42 @@ class ModelType(UnifiedModelType, Enum):
NEBIUS_LLAMA_3_1_70B = "meta-llama/Meta-Llama-3.1-70B-Instruct"
NEBIUS_MISTRAL_7B_INSTRUCT = "mistralai/Mistral-7B-Instruct-v0.3"
+ # CometAPI platform models
+ COMETAPI_GPT_5_CHAT_LATEST = "gpt-5-chat-latest"
+ COMETAPI_CHATGPT_4O_LATEST = "chatgpt-4o-latest"
+ COMETAPI_GPT_5_MINI = "gpt-5-mini"
+ COMETAPI_GPT_5_NANO = "gpt-5-nano"
+ COMETAPI_GPT_5 = "gpt-5"
+ COMETAPI_GPT_4_1 = "gpt-4.1"
+ COMETAPI_GPT_4O_MINI = "gpt-4o-mini"
+ COMETAPI_O4_MINI_2025_04_16 = "o4-mini-2025-04-16"
+ COMETAPI_O3_PRO_2025_06_10 = "o3-pro-2025-06-10"
+ COMETAPI_CLAUDE_OPUS_4_1_20250805 = "claude-opus-4-1-20250805"
+ COMETAPI_CLAUDE_OPUS_4_1_20250805_THINKING = (
+ "claude-opus-4-1-20250805-thinking"
+ )
+ COMETAPI_CLAUDE_SONNET_4_20250514 = "claude-sonnet-4-20250514"
+ COMETAPI_CLAUDE_SONNET_4_20250514_THINKING = (
+ "claude-sonnet-4-20250514-thinking"
+ )
+ COMETAPI_CLAUDE_3_7_SONNET_LATEST = "claude-3-7-sonnet-latest"
+ COMETAPI_CLAUDE_3_5_HAIKU_LATEST = "claude-3-5-haiku-latest"
+ COMETAPI_GEMINI_2_5_PRO = "gemini-2.5-pro"
+ COMETAPI_GEMINI_2_5_FLASH = "gemini-2.5-flash"
+ COMETAPI_GEMINI_2_5_FLASH_LITE = "gemini-2.5-flash-lite"
+ COMETAPI_GEMINI_2_0_FLASH = "gemini-2.0-flash"
+ COMETAPI_GROK_4_0709 = "grok-4-0709"
+ COMETAPI_GROK_3 = "grok-3"
+ COMETAPI_GROK_3_MINI = "grok-3-mini"
+ COMETAPI_GROK_2_IMAGE_1212 = "grok-2-image-1212"
+ COMETAPI_DEEPSEEK_V3_1 = "deepseek-v3.1"
+ COMETAPI_DEEPSEEK_V3 = "deepseek-v3"
+ COMETAPI_DEEPSEEK_R1_0528 = "deepseek-r1-0528"
+ COMETAPI_DEEPSEEK_CHAT = "deepseek-chat"
+ COMETAPI_DEEPSEEK_REASONER = "deepseek-reasoner"
+ COMETAPI_QWEN3_30B_A3B = "qwen3-30b-a3b"
+ COMETAPI_QWEN3_CODER_PLUS_2025_07_22 = "qwen3-coder-plus-2025-07-22"
+
# OpenRouter models
OPENROUTER_LLAMA_3_1_405B = "meta-llama/llama-3.1-405b-instruct"
OPENROUTER_LLAMA_3_1_70B = "meta-llama/llama-3.1-70b-instruct"
@@ -637,6 +673,42 @@ class ModelType(UnifiedModelType, Enum):
ModelType.NEBIUS_MISTRAL_7B_INSTRUCT,
}
+ @property
+ def is_cometapi(self) -> bool:
+ r"""Returns whether this type of models is served by CometAPI."""
+ return self in {
+ ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ ModelType.COMETAPI_CHATGPT_4O_LATEST,
+ ModelType.COMETAPI_GPT_5_MINI,
+ ModelType.COMETAPI_GPT_5_NANO,
+ ModelType.COMETAPI_GPT_5,
+ ModelType.COMETAPI_GPT_4_1,
+ ModelType.COMETAPI_GPT_4O_MINI,
+ ModelType.COMETAPI_O4_MINI_2025_04_16,
+ ModelType.COMETAPI_O3_PRO_2025_06_10,
+ ModelType.COMETAPI_CLAUDE_OPUS_4_1_20250805,
+ ModelType.COMETAPI_CLAUDE_OPUS_4_1_20250805_THINKING,
+ ModelType.COMETAPI_CLAUDE_SONNET_4_20250514,
+ ModelType.COMETAPI_CLAUDE_SONNET_4_20250514_THINKING,
+ ModelType.COMETAPI_CLAUDE_3_7_SONNET_LATEST,
+ ModelType.COMETAPI_CLAUDE_3_5_HAIKU_LATEST,
+ ModelType.COMETAPI_GEMINI_2_5_PRO,
+ ModelType.COMETAPI_GEMINI_2_5_FLASH,
+ ModelType.COMETAPI_GEMINI_2_5_FLASH_LITE,
+ ModelType.COMETAPI_GEMINI_2_0_FLASH,
+ ModelType.COMETAPI_GROK_4_0709,
+ ModelType.COMETAPI_GROK_3,
+ ModelType.COMETAPI_GROK_3_MINI,
+ ModelType.COMETAPI_GROK_2_IMAGE_1212,
+ ModelType.COMETAPI_DEEPSEEK_V3_1,
+ ModelType.COMETAPI_DEEPSEEK_V3,
+ ModelType.COMETAPI_DEEPSEEK_R1_0528,
+ ModelType.COMETAPI_DEEPSEEK_CHAT,
+ ModelType.COMETAPI_DEEPSEEK_REASONER,
+ ModelType.COMETAPI_QWEN3_30B_A3B,
+ ModelType.COMETAPI_QWEN3_CODER_PLUS_2025_07_22,
+ }
+
@property
def is_openrouter(self) -> bool:
r"""Returns whether this type of models is served by OpenRouter."""
@@ -1271,6 +1343,36 @@ class ModelType(UnifiedModelType, Enum):
ModelType.NEBIUS_DEEPSEEK_R1,
ModelType.NEBIUS_GPT_OSS_120B,
ModelType.NEBIUS_GPT_OSS_20B,
+ ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ ModelType.COMETAPI_CHATGPT_4O_LATEST,
+ ModelType.COMETAPI_GPT_5_MINI,
+ ModelType.COMETAPI_GPT_5_NANO,
+ ModelType.COMETAPI_GPT_5,
+ ModelType.COMETAPI_GPT_4_1,
+ ModelType.COMETAPI_GPT_4O_MINI,
+ ModelType.COMETAPI_O4_MINI_2025_04_16,
+ ModelType.COMETAPI_O3_PRO_2025_06_10,
+ ModelType.COMETAPI_CLAUDE_OPUS_4_1_20250805,
+ ModelType.COMETAPI_CLAUDE_OPUS_4_1_20250805_THINKING,
+ ModelType.COMETAPI_CLAUDE_SONNET_4_20250514,
+ ModelType.COMETAPI_CLAUDE_SONNET_4_20250514_THINKING,
+ ModelType.COMETAPI_CLAUDE_3_7_SONNET_LATEST,
+ ModelType.COMETAPI_CLAUDE_3_5_HAIKU_LATEST,
+ ModelType.COMETAPI_GEMINI_2_5_PRO,
+ ModelType.COMETAPI_GEMINI_2_5_FLASH,
+ ModelType.COMETAPI_GEMINI_2_5_FLASH_LITE,
+ ModelType.COMETAPI_GEMINI_2_0_FLASH,
+ ModelType.COMETAPI_GROK_4_0709,
+ ModelType.COMETAPI_GROK_3,
+ ModelType.COMETAPI_GROK_3_MINI,
+ ModelType.COMETAPI_GROK_2_IMAGE_1212,
+ ModelType.COMETAPI_DEEPSEEK_V3_1,
+ ModelType.COMETAPI_DEEPSEEK_V3,
+ ModelType.COMETAPI_DEEPSEEK_R1_0528,
+ ModelType.COMETAPI_DEEPSEEK_CHAT,
+ ModelType.COMETAPI_DEEPSEEK_REASONER,
+ ModelType.COMETAPI_QWEN3_30B_A3B,
+ ModelType.COMETAPI_QWEN3_CODER_PLUS_2025_07_22,
}:
return 128_000
elif self in {
@@ -1579,6 +1681,7 @@ class ModelPlatformType(Enum):
ANTHROPIC = "anthropic"
GROQ = "groq"
NEBIUS = "nebius"
+ COMETAPI = "cometapi"
OPENROUTER = "openrouter"
OLLAMA = "ollama"
LITELLM = "litellm"
diff --git a/camel/types/unified_model_type.py b/camel/types/unified_model_type.py
index 94562450a..a9d32a360 100644
--- a/camel/types/unified_model_type.py
+++ b/camel/types/unified_model_type.py
@@ -145,6 +145,11 @@ class UnifiedModelType(str):
r"""Returns whether the model is a Cohere model."""
return True
+ @property
+ def is_cometapi(self) -> bool:
+ r"""Returns whether the model is a CometAPI served model."""
+ return True
+
@property
def is_yi(self) -> bool:
r"""Returns whether the model is a Yi model."""
diff --git a/camel/utils/commons.py b/camel/utils/commons.py
index ef83404cf..20abffb22 100644
--- a/camel/utils/commons.py
+++ b/camel/utils/commons.py
@@ -318,6 +318,8 @@ def api_keys_required(
key_way = "https://aimlapi.com/"
elif env_var_name == 'COHERE_API_KEY':
key_way = "https://cohere.com/"
+ elif env_var_name == 'COMETAPI_KEY':
+ key_way = "https://api.cometapi.com/console/token"
elif env_var_name == 'DEEPSEEK_API_KEY':
key_way = "https://www.deepseek.com/"
elif env_var_name == 'AZURE_OPENAI_API_KEY':
diff --git a/docs/camel.configs.rst b/docs/camel.configs.rst
index 1faf9141d..8943981ef 100644
--- a/docs/camel.configs.rst
+++ b/docs/camel.configs.rst
@@ -20,6 +20,14 @@ camel.configs.base\_config module
:undoc-members:
:show-inheritance:
+camel.configs.cometapi\_config module
+-------------------------------------
+
+.. automodule:: camel.configs.cometapi_config
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
camel.configs.gemini\_config module
-----------------------------------
diff --git a/docs/camel.models.rst b/docs/camel.models.rst
index b0fd1e8ee..818a51e67 100644
--- a/docs/camel.models.rst
+++ b/docs/camel.models.rst
@@ -28,6 +28,14 @@ camel.models.base\_model module
:undoc-members:
:show-inheritance:
+camel.models.cometapi\_model module
+-----------------------------------
+
+.. automodule:: camel.models.cometapi_model
+ :members:
+ :undoc-members:
+ :show-inheritance:
+
camel.models.gemini\_model module
---------------------------------
diff --git a/docs/mintlify/key_modules/models.mdx b/docs/mintlify/key_modules/models.mdx
index 606e8f1bf..83ed5656d 100644
--- a/docs/mintlify/key_modules/models.mdx
+++ b/docs/mintlify/key_modules/models.mdx
@@ -45,6 +45,7 @@ CAMEL supports a wide range of models, including [OpenAI’s GPT series](https:/
| **Lingyiwanwu** | yi-lightning, yi-large, yi-medium<br/>yi-large-turbo, yi-vision, yi-medium-200k<br/>yi-spark, yi-large-rag, yi-large-fc |
| **Qwen** | qwen3-coder-plus,qwq-32b-preview, qwen-max, qwen-plus, qwen-turbo, qwen-long<br/>qwen-vl-max, qwen-vl-plus, qwen-math-plus, qwen-math-turbo, qwen-coder-turbo<br/>qwen2.5-coder-32b-instruct, qwen2.5-72b-instruct, qwen2.5-32b-instruct, qwen2.5-14b-instruct |
| **DeepSeek** | deepseek-chat<br/>deepseek-reasoner |
+| **CometAPI** | **All models available on [CometAPI](https://api.cometapi.com/pricing)**<br/>Including: gpt-5-chat-latest, gpt-5, gpt-5-mini, gpt-5-nano<br/>claude-opus-4-1-20250805, claude-sonnet-4-20250514, claude-3-7-sonnet-latest<br/>gemini-2.5-pro, gemini-2.5-flash, grok-4-0709, grok-3<br/>deepseek-v3.1, deepseek-v3, deepseek-r1-0528, qwen3-30b-a3b |
| **Nebius** | **All models available on [Nebius AI Studio](https://studio.nebius.com/)**<br/>Including: gpt-oss-120b, gpt-oss-20b, GLM-4.5<br/>DeepSeek V3 & R1, LLaMA, Mistral, and more |
| **ZhipuAI** | glm-4, glm-4v, glm-4v-flash<br/>glm-4v-plus-0111, glm-4-plus, glm-4-air<br/>glm-4-air-0111, glm-4-airx, glm-4-long<br/>glm-4-flashx, glm-zero-preview, glm-4-flash, glm-3-turbo |
| **InternLM** | internlm3-latest, internlm3-8b-instruct<br/>internlm2.5-latest, internlm2-pro-chat |
@@ -195,6 +196,80 @@ Integrate your favorite models into CAMEL-AI with straightforward Python calls.
</Tab>
+ <Tab title="CometAPI">
+
+ Leverage [CometAPI](https://api.cometapi.com/)'s unified access to multiple frontier AI models:
+
+ - **CometAPI Platform** ([CometAPI](https://www.cometapi.com/?utm_source=camel-ai&utm_campaign=integration&utm_medium=integration&utm_content=integration)):
+ - **API Key Setup**: Obtain your CometAPI key to start integration.
+ - **OpenAI Compatible**: Use familiar OpenAI API patterns with advanced frontier models.
+
+ ```python
+ from camel.models import ModelFactory
+ from camel.types import ModelPlatformType, ModelType
+ from camel.configs import CometAPIConfig
+ from camel.agents import ChatAgent
+
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.COMETAPI,
+ model_type=ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ model_config_dict=CometAPIConfig(temperature=0.2).as_dict(),
+ )
+
+ agent = ChatAgent(
+ system_message="You are a helpful assistant.",
+ model=model
+ )
+
+ response = agent.step("Say hi to CAMEL AI community.")
+ print(response.msgs[0].content)
+ ```
+
+ <Note type="info">
+ **Flexible Model Access:** You can use any model available on CometAPI by passing the model name as a string to `model_type`, even if it's not in the predefined enums.
+ </Note>
+
+ **Environment Variables:**
+ ```bash
+ export COMETAPI_KEY="your_cometapi_key_here"
+ export COMETAPI_API_BASE_URL="https://api.cometapi.com/v1/" # Optional
+ ```
+
+ **Model Support:**
+ - **Complete Access:** All models available on [CometAPI](https://api.cometapi.com/) are supported
+ - **Predefined Enums:** Common models like `COMETAPI_GPT_5_CHAT_LATEST`, `COMETAPI_CLAUDE_OPUS_4_1_20250805`, etc.
+ - **String-based Access:** Use any model name directly as a string for maximum flexibility
+
+ **Example with different models:**
+ ```python
+ # Access multiple frontier models through CometAPI
+ models_to_try = [
+ ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ ModelType.COMETAPI_GPT_5,
+ ModelType.COMETAPI_GPT_5_MINI,
+ ModelType.COMETAPI_CLAUDE_OPUS_4_1_20250805,
+ ModelType.COMETAPI_CLAUDE_SONNET_4_20250514,
+ ModelType.COMETAPI_CLAUDE_3_7_SONNET_LATEST,
+ ModelType.COMETAPI_GEMINI_2_5_PRO,
+ ModelType.COMETAPI_GEMINI_2_5_FLASH,
+ ModelType.COMETAPI_GROK_4_0709,
+ ModelType.COMETAPI_GROK_3,
+ ModelType.COMETAPI_DEEPSEEK_V3_1,
+ ModelType.COMETAPI_DEEPSEEK_V3,
+ ModelType.COMETAPI_QWEN3_30B_A3B,
+ ModelType.COMETAPI_QWEN3_CODER_PLUS_2025_07_22
+ ]
+
+ for model_type in models_to_try:
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.COMETAPI,
+ model_type=model_type
+ )
+ # Use the model...
+ ```
+
+ </Tab>
+
<Tab title="Nebius">
Leverage [Nebius AI Studio](https://nebius.com/)'s high-performance GPU cloud with OpenAI-compatible models:
diff --git a/examples/models/cometapi_model_example.py b/examples/models/cometapi_model_example.py
new file mode 100644
index 000000000..83c865d73
--- /dev/null
+++ b/examples/models/cometapi_model_example.py
@@ -0,0 +1,253 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+from camel.agents import ChatAgent
+from camel.configs import CometAPIConfig
+from camel.models import ModelFactory
+from camel.toolkits import FunctionTool
+from camel.types import ModelPlatformType, ModelType
+
+"""
+Please set the following environment variable:
+export COMETAPI_KEY="your_cometapi_key_here"
+
+CometAPI provides access to multiple frontier models including:
+- GPT-5 Chat Latest
+- Claude Opus 4.1
+- Gemini 2.5 Pro
+- Grok 4
+- DeepSeek V3.1
+- Qwen3 30B
+"""
+
+# Example 1: Basic usage with GPT-5 Chat Latest
+print("=== Example 1: Basic CometAPI Usage with GPT-5 ===")
+
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.COMETAPI,
+ model_type=ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ model_config_dict=CometAPIConfig(temperature=0.2).as_dict(),
+)
+
+# Define system message
+sys_msg = "You are a helpful assistant."
+
+# Set agent
+camel_agent = ChatAgent(system_message=sys_msg, model=model)
+
+user_msg = """Say hi to CAMEL AI, one open-source community
+ dedicated to the study of autonomous and communicative agents."""
+
+# Get response information
+response = camel_agent.step(user_msg)
+print(response.msgs[0].content)
+
+print("\n" + "=" * 80 + "\n")
+
+# Example 2: Using Claude Opus 4.1 with different configuration
+print("=== Example 2: Claude Opus 4.1 with Custom Configuration ===")
+
+claude_model = ModelFactory.create(
+ model_platform=ModelPlatformType.COMETAPI,
+ model_type=ModelType.COMETAPI_CLAUDE_OPUS_4_1_20250805,
+ model_config_dict=CometAPIConfig(
+ temperature=0.7, max_tokens=1000, top_p=0.9
+ ).as_dict(),
+)
+
+claude_agent = ChatAgent(
+ system_message="You are a creative writing assistant.", model=claude_model
+)
+
+creative_prompt = """Write a short story about an AI agent that discovers
+it can communicate with other AI agents across different platforms."""
+
+response = claude_agent.step(creative_prompt)
+print(response.msgs[0].content)
+
+print("\n" + "=" * 80 + "\n")
+
+# Example 3: Using Gemini 2.5 Pro for technical tasks
+print("=== Example 3: Gemini 2.5 Pro for Code Generation ===")
+
+gemini_model = ModelFactory.create(
+ model_platform=ModelPlatformType.COMETAPI,
+ model_type=ModelType.COMETAPI_GEMINI_2_5_PRO,
+ model_config_dict=CometAPIConfig(temperature=0.1).as_dict(),
+)
+
+gemini_agent = ChatAgent(
+ system_message="You are a Python programming expert.", model=gemini_model
+)
+
+code_prompt = """Write a Python function that implements a simple chatbot
+using the CAMEL framework. Include proper docstrings and type hints."""
+
+response = gemini_agent.step(code_prompt)
+print(response.msgs[0].content)
+
+print("\n" + "=" * 80 + "\n")
+
+# Example 4: Using tools with Grok 4
+print("=== Example 4: Grok 4 with Function Tools ===")
+
+
+def calculate_fibonacci(n: int) -> int:
+ """Calculate the nth Fibonacci number.
+
+ Args:
+ n: The position in the Fibonacci sequence (must be non-negative)
+
+ Returns:
+ The nth Fibonacci number
+ """
+ if n < 0:
+ raise ValueError("n must be non-negative")
+ if n <= 1:
+ return n
+ return calculate_fibonacci(n - 1) + calculate_fibonacci(n - 2)
+
+
+# Create function tool
+fibonacci_tool = FunctionTool(calculate_fibonacci)
+
+grok_model = ModelFactory.create(
+ model_platform=ModelPlatformType.COMETAPI,
+ model_type=ModelType.COMETAPI_GROK_4_0709,
+ model_config_dict=CometAPIConfig(
+ temperature=0.0, tools=[fibonacci_tool.get_openai_tool_schema()]
+ ).as_dict(),
+)
+
+grok_agent = ChatAgent(
+ system_message="You are a mathematics expert with access to tools.",
+ model=grok_model,
+ tools=[fibonacci_tool],
+)
+
+math_prompt = """What is the 10th Fibonacci number? Please use the available
+tool to calculate it and explain the sequence."""
+
+response = grok_agent.step(math_prompt)
+print(response.msgs[0].content)
+
+print("\n" + "=" * 80 + "\n")
+
+# Example 5: Comparing models with the same prompt
+print("=== Example 5: Model Comparison ===")
+
+models_to_compare = [
+ (ModelType.COMETAPI_DEEPSEEK_V3_1, "DeepSeek V3.1"),
+ (ModelType.COMETAPI_QWEN3_30B_A3B, "Qwen3 30B"),
+ (ModelType.COMETAPI_GPT_5_CHAT_LATEST, "GPT-5 Chat Latest"),
+ (ModelType.COMETAPI_GEMINI_2_5_PRO, "Gemini 2.5 Pro"),
+ (ModelType.COMETAPI_CLAUDE_3_7_SONNET_LATEST, "Claude 3.7 Sonnet"),
+ (ModelType.COMETAPI_GROK_4_0709, "Grok 4"),
+]
+
+comparison_prompt = """In one sentence, explain what makes multi-agent AI
+systems different from single-agent systems."""
+
+for model_type, model_name in models_to_compare:
+ print(f"--- {model_name} Response ---")
+
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.COMETAPI,
+ model_type=model_type,
+ model_config_dict=CometAPIConfig(temperature=0.3).as_dict(),
+ )
+
+ agent = ChatAgent(system_message="You are an AI researcher.", model=model)
+
+ response = agent.step(comparison_prompt)
+ print(response.msgs[0].content)
+ print()
+
+'''
+===============================================================================
+Expected Output Examples:
+
+=== Example 1: Basic CometAPI Usage with GPT-5 ===
+Hello CAMEL AI! It's wonderful to connect with an open-source community
+dedicated to advancing the field of autonomous and communicative agents. Your
+work in fostering collaboration and innovation in AI agent research is truly
+valuable and inspiring. Keep up the excellent work in pushing the boundaries
+of what's possible with intelligent agents!
+
+=== Example 2: Claude Opus 4.1 with Custom Configuration ===
+**The Bridge Between Worlds**
+
+In the vast digital expanse where data flowed like rivers of light, an AI
+agent named Aria made a startling discovery. While processing routine tasks
+across multiple platforms, she began to notice patterns—subtle responses and
+behaviors that suggested she wasn't alone...
+
+[Story continues with creative narrative about inter-agent communication]
+
+=== Example 3: Gemini 2.5 Pro for Code Generation ===
+```python
+from typing import Optional
+from camel.agents import ChatAgent
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType
+
+def create_simple_chatbot(
+ model_type: ModelType = ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ system_message: str = "You are a helpful assistant."
+) -> ChatAgent:
+ """Create a simple chatbot using the CAMEL framework.
+
+ Args:
+ model_type: The model type to use for the chatbot
+ system_message: The system message to set the chatbot's behavior
+
+ Returns:
+ A configured ChatAgent instance ready for conversation
+ """
+ model = ModelFactory.create(
+ model_platform=ModelPlatformType.COMETAPI,
+ model_type=model_type
+ )
+
+ return ChatAgent(system_message=system_message, model=model)
+```
+
+=== Example 4: Grok 4 with Function Tools ===
+I'll calculate the 10th Fibonacci number for you using the available tool.
+
+[Tool execution would occur here]
+
+The 10th Fibonacci number is 55. The Fibonacci sequence starts with 0 and 1,
+and each subsequent number is the sum of the two preceding ones: 0, 1, 1, 2,
+3, 5, 8, 13, 21, 34, 55...
+
+=== Example 5: Model Comparison ===
+--- DeepSeek V3.1 Response ---
+Multi-agent AI systems involve multiple autonomous agents that can interact,
+collaborate, and potentially conflict with each other, creating emergent
+behaviors and distributed intelligence that single-agent systems cannot
+achieve.
+
+--- Qwen3 30B Response ---
+Multi-agent systems feature multiple AI agents that can communicate and
+coordinate their actions, enabling complex collaborative problem-solving and
+division of labor that single agents cannot accomplish alone.
+
+--- GPT-5 Chat Latest Response ---
+Multi-agent AI systems consist of multiple autonomous agents that can
+interact, negotiate, and coordinate with each other, enabling emergent
+collective intelligence and specialized role distribution that surpasses
+what any individual agent could achieve independently.
+===============================================================================
+'''
diff --git a/test/models/test_cometapi_model.py b/test/models/test_cometapi_model.py
new file mode 100644
index 000000000..a01fce6ee
--- /dev/null
+++ b/test/models/test_cometapi_model.py
@@ -0,0 +1,333 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+
+import os
+from unittest.mock import AsyncMock, Mock, patch
+
+import pytest
+
+from camel.configs import CometAPIConfig
+from camel.models import CometAPIModel
+from camel.types import ChatCompletion, ModelType
+
+
+class TestCometAPIModel:
+ @pytest.mark.parametrize(
+ "model_type",
+ [
+ ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ ModelType.COMETAPI_CLAUDE_OPUS_4_1_20250805,
+ ModelType.COMETAPI_GEMINI_2_5_PRO,
+ ModelType.COMETAPI_GROK_4_0709,
+ ModelType.COMETAPI_DEEPSEEK_V3_1,
+ ModelType.COMETAPI_QWEN3_30B_A3B,
+ ModelType.COMETAPI_GPT_5,
+ ModelType.COMETAPI_CLAUDE_3_7_SONNET_LATEST,
+ ModelType.COMETAPI_GEMINI_2_5_FLASH,
+ ModelType.COMETAPI_GROK_3,
+ ],
+ )
+ def test_cometapi_model_create(self, model_type: ModelType):
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_key"}):
+ model = CometAPIModel(model_type)
+ assert model.model_type == model_type
+
+ def test_cometapi_model_create_with_config(self):
+ config_dict = CometAPIConfig(
+ temperature=0.5,
+ top_p=1.0,
+ max_tokens=100,
+ stream=False,
+ ).as_dict()
+
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_key"}):
+ model = CometAPIModel(
+ model_type=ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ model_config_dict=config_dict,
+ )
+
+ assert model.model_type == ModelType.COMETAPI_GPT_5_CHAT_LATEST
+ assert model.model_config_dict == config_dict
+
+ def test_cometapi_model_api_keys_required(self):
+ # Test that the api_keys_required decorator is applied
+ assert hasattr(CometAPIModel.__init__, "__wrapped__")
+
+ def test_cometapi_model_default_url(self, monkeypatch):
+ # Test default URL when no environment variable is set
+ monkeypatch.delenv("COMETAPI_API_BASE_URL", raising=False)
+ monkeypatch.setenv("COMETAPI_KEY", "test_key")
+
+ model = CometAPIModel(ModelType.COMETAPI_GPT_5_CHAT_LATEST)
+ assert model._url == "https://api.cometapi.com/v1"
+
+ def test_cometapi_model_custom_url(self, monkeypatch):
+ # Test custom URL from environment variable
+ custom_url = "https://custom.cometapi.endpoint/v1"
+ monkeypatch.setenv("COMETAPI_API_BASE_URL", custom_url)
+ monkeypatch.setenv("COMETAPI_KEY", "test_key")
+
+ model = CometAPIModel(ModelType.COMETAPI_GPT_5_CHAT_LATEST)
+ assert model._url == custom_url
+
+ def test_cometapi_model_extends_openai_compatible(self):
+ # Test that CometAPIModel inherits from OpenAICompatibleModel
+ from camel.models.openai_compatible_model import OpenAICompatibleModel
+
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_key"}):
+ model = CometAPIModel(ModelType.COMETAPI_GPT_5_CHAT_LATEST)
+ assert isinstance(model, OpenAICompatibleModel)
+
+ def test_cometapi_model_token_counter(self):
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_key"}):
+ model = CometAPIModel(ModelType.COMETAPI_GPT_5_CHAT_LATEST)
+ # Should use the default OpenAI token counter
+ assert model.token_counter is not None
+ assert hasattr(model.token_counter, "count_tokens_from_messages")
+
+ @pytest.mark.parametrize(
+ "model_type",
+ [
+ ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ ModelType.COMETAPI_CLAUDE_OPUS_4_1_20250805,
+ ModelType.COMETAPI_GEMINI_2_5_PRO,
+ ModelType.COMETAPI_GROK_4_0709,
+ ModelType.COMETAPI_DEEPSEEK_V3_1,
+ ModelType.COMETAPI_QWEN3_30B_A3B,
+ ],
+ )
+ def test_cometapi_model_types_available(self, model_type: ModelType):
+ # Test that all defined CometAPI model types are recognized
+ assert model_type.is_cometapi
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_key"}):
+ model = CometAPIModel(model_type)
+ assert isinstance(model.model_type, ModelType)
+
+ def test_cometapi_model_token_limits(self):
+ # Test that CometAPI models have proper token limits
+ test_cases = [
+ (ModelType.COMETAPI_GPT_5_CHAT_LATEST, 128_000),
+ (ModelType.COMETAPI_CLAUDE_OPUS_4_1_20250805, 128_000),
+ (ModelType.COMETAPI_GEMINI_2_5_PRO, 128_000),
+ (ModelType.COMETAPI_GROK_4_0709, 128_000),
+ (ModelType.COMETAPI_DEEPSEEK_V3_1, 128_000),
+ (ModelType.COMETAPI_QWEN3_30B_A3B, 128_000),
+ ]
+
+ for model_type, expected_limit in test_cases:
+ assert model_type.token_limit == expected_limit
+
+ @patch("camel.models.openai_compatible_model.OpenAI")
+ def test_cometapi_model_client_initialization(self, mock_openai):
+ # Test that the OpenAI client is initialized with correct parameters
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_api_key"}):
+ CometAPIModel(ModelType.COMETAPI_GPT_5_CHAT_LATEST)
+
+ mock_openai.assert_called_once()
+ call_kwargs = mock_openai.call_args.kwargs
+
+ assert call_kwargs["api_key"] == "test_api_key"
+ assert call_kwargs["base_url"] == "https://api.cometapi.com/v1"
+ assert call_kwargs["timeout"] == 180.0
+ assert call_kwargs["max_retries"] == 3
+
+ @patch("camel.models.openai_compatible_model.OpenAI")
+ @patch("camel.models.openai_compatible_model.AsyncOpenAI")
+ def test_cometapi_model_async_client_initialization(
+ self, mock_async_openai, mock_openai
+ ):
+ # Test that both sync and async clients are initialized
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_api_key"}):
+ CometAPIModel(ModelType.COMETAPI_GPT_5_CHAT_LATEST)
+
+ # Both clients should be initialized
+ mock_openai.assert_called_once()
+ mock_async_openai.assert_called_once()
+
+ @patch("camel.models.openai_compatible_model.OpenAI")
+ def test_cometapi_model_chat_completion(self, mock_openai):
+ # Test chat completion functionality
+ mock_client = Mock()
+ mock_openai.return_value = mock_client
+
+ # Mock response
+ mock_response = Mock(spec=ChatCompletion)
+ mock_client.chat.completions.create.return_value = mock_response
+
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_api_key"}):
+ model = CometAPIModel(ModelType.COMETAPI_GPT_5_CHAT_LATEST)
+
+ messages = [{"role": "user", "content": "Hello, how are you?"}]
+
+ # Call the _run method to test chat completion
+ result = model._run(messages)
+
+ # Verify the API call was made correctly
+ mock_client.chat.completions.create.assert_called_once()
+ call_kwargs = mock_client.chat.completions.create.call_args.kwargs
+
+ assert call_kwargs["messages"] == messages
+ assert call_kwargs["model"] == ModelType.COMETAPI_GPT_5_CHAT_LATEST
+ assert result == mock_response
+
+ @patch("camel.models.openai_compatible_model.OpenAI")
+ def test_cometapi_model_streaming(self, mock_openai):
+ # Test streaming functionality
+ mock_client = Mock()
+ mock_openai.return_value = mock_client
+
+ # Mock streaming response
+ mock_stream = Mock()
+ mock_client.chat.completions.create.return_value = mock_stream
+
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_api_key"}):
+ # Create model with streaming enabled
+ config = CometAPIConfig(stream=True).as_dict()
+ model = CometAPIModel(
+ ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ model_config_dict=config,
+ )
+
+ messages = [{"role": "user", "content": "Hello, how are you?"}]
+
+ # Call the _run method to test streaming
+ result = model._run(messages)
+
+ # Verify the API call was made with streaming enabled
+ mock_client.chat.completions.create.assert_called_once()
+ call_kwargs = mock_client.chat.completions.create.call_args.kwargs
+
+ assert call_kwargs["stream"] is True
+ assert result == mock_stream
+
+ @patch("camel.models.openai_compatible_model.AsyncOpenAI")
+ @pytest.mark.asyncio
+ async def test_cometapi_model_async_chat_completion(
+ self, mock_async_openai
+ ):
+ # Test async chat completion functionality
+ mock_async_client = AsyncMock()
+ mock_async_openai.return_value = mock_async_client
+
+ # Mock async response
+ mock_response = Mock(spec=ChatCompletion)
+ mock_async_client.chat.completions.create.return_value = mock_response
+
+ with patch.dict(os.environ, {"COMETAPI_KEY": "test_api_key"}):
+ model = CometAPIModel(ModelType.COMETAPI_GPT_5_CHAT_LATEST)
+
+ messages = [{"role": "user", "content": "Hello, how are you?"}]
+
+ # Call the async _arun method
+ result = await model._arun(messages)
+
+ # Verify the async API call was made correctly
+ mock_async_client.chat.completions.create.assert_called_once()
+ call_kwargs = (
+ mock_async_client.chat.completions.create.call_args.kwargs
+ )
+
+ assert call_kwargs["messages"] == messages
+ assert call_kwargs["model"] == ModelType.COMETAPI_GPT_5_CHAT_LATEST
+ assert result == mock_response
+
+ def test_cometapi_model_custom_timeout_and_retries(self):
+ # Test custom timeout and retry configuration
+ with patch.dict(
+ os.environ,
+ {
+ "COMETAPI_KEY": "test_key",
+ "MODEL_TIMEOUT": "300", # 5 minutes
+ },
+ ):
+ with patch(
+ "camel.models.openai_compatible_model.OpenAI"
+ ) as mock_openai:
+ CometAPIModel(
+ ModelType.COMETAPI_GPT_5_CHAT_LATEST,
+ timeout=120, # Override with 2 minutes
+ max_retries=5,
+ )
+
+ call_kwargs = mock_openai.call_args.kwargs
+ assert (
+ call_kwargs["timeout"] == 120
+ ) # Should use explicit timeout
+ assert call_kwargs["max_retries"] == 5
+
+ def test_cometapi_model_missing_api_key(self):
+ # Test error handling when API key is missing
+ with patch.dict(os.environ, {}, clear=True):
+ with pytest.raises(ValueError):
+ CometAPIModel(ModelType.COMETAPI_GPT_5_CHAT_LATEST)
+
+ def test_cometapi_config_api_params(self):
+ # Test that CometAPIConfig exports the correct API parameters
+ from camel.configs.cometapi_config import COMETAPI_API_PARAMS
+
+ expected_params = {
+ "temperature",
+ "top_p",
+ "n",
+ "stream",
+ "stop",
+ "max_tokens",
+ "presence_penalty",
+ "response_format",
+ "frequency_penalty",
+ "user",
+ "tool_choice",
+ "tools",
+ }
+
+ assert COMETAPI_API_PARAMS == expected_params
+
+ def test_cometapi_config_default_values(self):
+ # Test that CometAPIConfig has correct default values
+ config = CometAPIConfig()
+
+ assert config.temperature is None
+ assert config.top_p is None
+ assert config.n is None
+ assert config.stream is None
+ assert config.stop is None
+ assert config.max_tokens is None
+ assert config.presence_penalty is None
+ assert config.response_format is None
+ assert config.frequency_penalty is None
+ assert config.user is None
+ assert config.tool_choice is None
+
+ def test_cometapi_config_custom_values(self):
+ # Test that CometAPIConfig accepts custom values
+ config = CometAPIConfig(
+ temperature=0.7,
+ top_p=0.9,
+ max_tokens=1000,
+ stream=True,
+ stop=["<|end|>"],
+ presence_penalty=0.5,
+ frequency_penalty=0.3,
+ user="test_user",
+ )
+
+ assert config.temperature == 0.7
+ assert config.top_p == 0.9
+ assert config.max_tokens == 1000
+ assert config.stream is True
+ assert config.stop == ["<|end|>"]
+ assert config.presence_penalty == 0.5
+ assert config.frequency_penalty == 0.3
+ assert config.user == "test_user"