Skip to content

Commit d4fa167

Browse files
feat: Add CometAPI support with new model and configuration classes (#3169)
Co-authored-by: Wendong-Fan <133094783+Wendong-Fan@users.noreply.github.com>
1 parent 1f6de99 commit d4fa167

File tree

15 files changed

+985
-0
lines changed

15 files changed

+985
-0
lines changed

.github/workflows/build_package.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ jobs:
142142
BOHRIUM_API_KEY: "${{ secrets.BOHRIUM_API_KEY }}"
143143
CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
144144
NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"
145+
COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"
145146
run: |
146147
source test_venv/bin/activate
147148
pytest --fast-test-mode -m "not heavy_dependency" \

.github/workflows/pytest_package.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ jobs:
8181
BOHRIUM_API_KEY: "${{ secrets.BOHRIUM_API_KEY }}"
8282
CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
8383
NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"
84+
COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"
8485
run: |
8586
source .venv/bin/activate
8687
uv pip install -e ".[all, dev, docs]"
@@ -167,6 +168,7 @@ jobs:
167168
CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
168169
NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"
169170
AMD_API_KEY: "${{ secrets.AMD_API_KEY }}"
171+
COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"
170172
run: |
171173
source .venv/bin/activate
172174
uv pip install -e ".[all, dev, docs]"
@@ -251,6 +253,7 @@ jobs:
251253
CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
252254
NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"
253255
AMD_API_KEY: "${{ secrets.AMD_API_KEY }}"
256+
COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"
254257
run: |
255258
source .venv/bin/activate
256259
uv pip install -e ".[all, dev, docs]"

camel/configs/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from .base_config import BaseConfig
1818
from .bedrock_config import BEDROCK_API_PARAMS, BedrockConfig
1919
from .cohere_config import COHERE_API_PARAMS, CohereConfig
20+
from .cometapi_config import COMETAPI_API_PARAMS, CometAPIConfig
2021
from .crynux_config import CRYNUX_API_PARAMS, CrynuxConfig
2122
from .deepseek_config import DEEPSEEK_API_PARAMS, DeepSeekConfig
2223
from .gemini_config import Gemini_API_PARAMS, GeminiConfig
@@ -90,6 +91,8 @@
9091
'TOGETHERAI_API_PARAMS',
9192
'CohereConfig',
9293
'COHERE_API_PARAMS',
94+
'CometAPIConfig',
95+
'COMETAPI_API_PARAMS',
9396
'YiConfig',
9497
'YI_API_PARAMS',
9598
'QwenConfig',

camel/configs/cometapi_config.py

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14+
from __future__ import annotations
15+
16+
from typing import Optional, Sequence, Union
17+
18+
from camel.configs.base_config import BaseConfig
19+
20+
21+
class CometAPIConfig(BaseConfig):
22+
r"""Defines the parameters for generating chat completions using CometAPI's
23+
OpenAI-compatible interface.
24+
25+
Reference: https://api.cometapi.com/v1/
26+
27+
Args:
28+
temperature (float, optional): Sampling temperature to use, between
29+
:obj:`0` and :obj:`2`. Higher values make the output more random,
30+
while lower values make it more focused and deterministic.
31+
(default: :obj:`None`)
32+
top_p (float, optional): An alternative to sampling with temperature,
33+
called nucleus sampling, where the model considers the results of
34+
the tokens with top_p probability mass. So :obj:`0.1` means only
35+
the tokens comprising the top 10% probability mass are considered.
36+
(default: :obj:`None`)
37+
n (int, optional): How many chat completion choices to generate for
38+
each input message. (default: :obj:`None`)
39+
response_format (object, optional): An object specifying the format
40+
that the model must output. Compatible with GPT-4 Turbo and all
41+
GPT-3.5 Turbo models newer than gpt-3.5-turbo-1106. Setting to
42+
{"type": "json_object"} enables JSON mode, which guarantees the
43+
message the model generates is valid JSON. Important: when using
44+
JSON mode, you must also instruct the model to produce JSON
45+
yourself via a system or user message. Without this, the model
46+
may generate an unending stream of whitespace until the generation
47+
reaches the token limit, resulting in a long-running and seemingly
48+
"stuck" request. Also note that the message content may be
49+
partially cut off if finish_reason="length", which indicates the
50+
generation exceeded max_tokens or the conversation exceeded the
51+
max context length.
52+
stream (bool, optional): If True, partial message deltas will be sent
53+
as data-only server-sent events as they become available.
54+
(default: :obj:`None`)
55+
stop (str or list, optional): Up to :obj:`4` sequences where the API
56+
will stop generating further tokens. (default: :obj:`None`)
57+
max_tokens (int, optional): The maximum number of tokens to generate
58+
in the chat completion. The total length of input tokens and
59+
generated tokens is limited by the model's context length.
60+
(default: :obj:`None`)
61+
presence_penalty (float, optional): Number between :obj:`-2.0` and
62+
:obj:`2.0`. Positive values penalize new tokens based on whether
63+
they appear in the text so far, increasing the model's likelihood
64+
to talk about new topics. See more information about frequency and
65+
presence penalties. (default: :obj:`None`)
66+
frequency_penalty (float, optional): Number between :obj:`-2.0` and
67+
:obj:`2.0`. Positive values penalize new tokens based on their
68+
existing frequency in the text so far, decreasing the model's
69+
likelihood to repeat the same line verbatim. See more information
70+
about frequency and presence penalties. (default: :obj:`None`)
71+
user (str, optional): A unique identifier representing your end-user,
72+
which can help CometAPI to monitor and detect abuse.
73+
(default: :obj:`None`)
74+
tools (list[FunctionTool], optional): A list of tools the model may
75+
call. Currently, only functions are supported as a tool. Use this
76+
to provide a list of functions the model may generate JSON inputs
77+
for. A max of 128 functions are supported.
78+
tool_choice (Union[dict[str, str], str], optional): Controls which (if
79+
any) tool is called by the model. :obj:`"none"` means the model
80+
will not call any tool and instead generates a message.
81+
:obj:`"auto"` means the model can pick between generating a
82+
message or calling one or more tools. :obj:`"required"` means the
83+
model must call one or more tools. Specifying a particular tool
84+
via {"type": "function", "function": {"name": "my_function"}}
85+
forces the model to call that tool. :obj:`"none"` is the default
86+
when no tools are present. :obj:`"auto"` is the default if tools
87+
are present.
88+
"""
89+
90+
temperature: Optional[float] = None
91+
top_p: Optional[float] = None
92+
n: Optional[int] = None
93+
stream: Optional[bool] = None
94+
stop: Optional[Union[str, Sequence[str]]] = None
95+
max_tokens: Optional[int] = None
96+
presence_penalty: Optional[float] = None
97+
response_format: Optional[dict] = None
98+
frequency_penalty: Optional[float] = None
99+
user: Optional[str] = None
100+
tools: Optional[list] = None
101+
tool_choice: Optional[Union[dict[str, str], str]] = None
102+
103+
104+
COMETAPI_API_PARAMS = {param for param in CometAPIConfig.model_fields.keys()}

camel/models/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from .base_audio_model import BaseAudioModel
2020
from .base_model import BaseModelBackend
2121
from .cohere_model import CohereModel
22+
from .cometapi_model import CometAPIModel
2223
from .crynux_model import CrynuxModel
2324
from .deepseek_model import DeepSeekModel
2425
from .fish_audio_model import FishAudioModel
@@ -69,6 +70,7 @@
6970
'StubModel',
7071
'ZhipuAIModel',
7172
'CohereModel',
73+
'CometAPIModel',
7274
'ModelFactory',
7375
'ModelManager',
7476
'LiteLLMModel',

camel/models/cometapi_model.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
#
6+
# http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14+
import os
15+
from typing import Any, Dict, Optional, Union
16+
17+
from camel.configs import CometAPIConfig
18+
from camel.models.openai_compatible_model import OpenAICompatibleModel
19+
from camel.types import ModelType
20+
from camel.utils import (
21+
BaseTokenCounter,
22+
api_keys_required,
23+
)
24+
25+
26+
class CometAPIModel(OpenAICompatibleModel):
27+
r"""LLM API served by CometAPI in a unified OpenAICompatibleModel
28+
interface.
29+
30+
Args:
31+
model_type (Union[ModelType, str]): Model for which a backend is
32+
created.
33+
model_config_dict (Optional[Dict[str, Any]], optional): A dictionary
34+
that will be fed into:obj:`openai.ChatCompletion.create()`.
35+
If:obj:`None`, :obj:`CometAPIConfig().as_dict()` will be used.
36+
(default: :obj:`None`)
37+
api_key (Optional[str], optional): The API key for authenticating
38+
with the CometAPI service. (default: :obj:`None`).
39+
url (Optional[str], optional): The url to the CometAPI service.
40+
(default: :obj:`None`)
41+
token_counter (Optional[BaseTokenCounter], optional): Token counter to
42+
use for the model. If not provided, :obj:`OpenAITokenCounter(
43+
ModelType.GPT_4O_MINI)` will be used.
44+
(default: :obj:`None`)
45+
timeout (Optional[float], optional): The timeout value in seconds for
46+
API calls. If not provided, will fall back to the MODEL_TIMEOUT
47+
environment variable or default to 180 seconds.
48+
(default: :obj:`None`)
49+
max_retries (int, optional): Maximum number of retries for API calls.
50+
(default: :obj:`3`)
51+
**kwargs (Any): Additional arguments to pass to the client
52+
initialization.
53+
"""
54+
55+
@api_keys_required([("api_key", "COMETAPI_KEY")])
56+
def __init__(
57+
self,
58+
model_type: Union[ModelType, str],
59+
model_config_dict: Optional[Dict[str, Any]] = None,
60+
api_key: Optional[str] = None,
61+
url: Optional[str] = None,
62+
token_counter: Optional[BaseTokenCounter] = None,
63+
timeout: Optional[float] = None,
64+
max_retries: int = 3,
65+
**kwargs: Any,
66+
) -> None:
67+
if model_config_dict is None:
68+
model_config_dict = CometAPIConfig().as_dict()
69+
api_key = api_key or os.environ.get("COMETAPI_KEY")
70+
url = url or os.environ.get(
71+
"COMETAPI_API_BASE_URL", "https://api.cometapi.com/v1"
72+
)
73+
timeout = timeout or float(os.environ.get("MODEL_TIMEOUT", 180))
74+
super().__init__(
75+
model_type=model_type,
76+
model_config_dict=model_config_dict,
77+
api_key=api_key,
78+
url=url,
79+
token_counter=token_counter,
80+
timeout=timeout,
81+
max_retries=max_retries,
82+
**kwargs,
83+
)

camel/models/model_factory.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from camel.models.azure_openai_model import AzureOpenAIModel
2323
from camel.models.base_model import BaseModelBackend
2424
from camel.models.cohere_model import CohereModel
25+
from camel.models.cometapi_model import CometAPIModel
2526
from camel.models.crynux_model import CrynuxModel
2627
from camel.models.deepseek_model import DeepSeekModel
2728
from camel.models.gemini_model import GeminiModel
@@ -86,6 +87,7 @@ class ModelFactory:
8687
ModelPlatformType.AZURE: AzureOpenAIModel,
8788
ModelPlatformType.ANTHROPIC: AnthropicModel,
8889
ModelPlatformType.GROQ: GroqModel,
90+
ModelPlatformType.COMETAPI: CometAPIModel,
8991
ModelPlatformType.NEBIUS: NebiusModel,
9092
ModelPlatformType.LMSTUDIO: LMStudioModel,
9193
ModelPlatformType.OPENROUTER: OpenRouterModel,

0 commit comments

Comments
 (0)