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 Crynux as a LLM provider (#2508)

0xaaaaaron771f17df1cb1
diff --git a/.github/workflows/build_package.yml b/.github/workflows/build_package.yml
index f9bd979e4..6201bf956 100644
--- a/.github/workflows/build_package.yml
+++ b/.github/workflows/build_package.yml
@@ -138,6 +138,7 @@ jobs:
WATSONX_PROJECT_ID: "${{ secrets.WATSONX_PROJECT_ID }}"
ACI_API_KEY: "${{ secrets.ACI_API_KEY }}"
BOHRIUM_API_KEY: "${{ secrets.BOHRIUM_API_KEY }}"
+ CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
run: |
source test_venv/bin/activate
pytest --fast-test-mode ./test
diff --git a/.github/workflows/pytest_package.yml b/.github/workflows/pytest_package.yml
index dfe2ffeee..841adc62e 100644
--- a/.github/workflows/pytest_package.yml
+++ b/.github/workflows/pytest_package.yml
@@ -77,6 +77,7 @@ jobs:
WATSONX_PROJECT_ID: "${{ secrets.WATSONX_PROJECT_ID }}"
ACI_API_KEY: "${{ secrets.ACI_API_KEY }}"
BOHRIUM_API_KEY: "${{ secrets.BOHRIUM_API_KEY }}"
+ CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
run: |
source .venv/bin/activate
uv pip install -e ".[all, dev, docs]"
@@ -146,6 +147,7 @@ jobs:
WATSONX_PROJECT_ID: "${{ secrets.WATSONX_PROJECT_ID }}"
ACI_API_KEY: "${{ secrets.ACI_API_KEY }}"
BOHRIUM_API_KEY: "${{ secrets.BOHRIUM_API_KEY }}"
+ CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"
run: |
source .venv/bin/activate
uv pip install -e ".[all, dev, docs]"
@@ -213,6 +215,7 @@ jobs:
WATSONX_PROJECT_ID: "${{ secrets.WATSONX_PROJECT_ID }}"
ACI_API_KEY: "${{ secrets.ACI_API_KEY }}"
BOHRIUM_API_KEY: "${{ secrets.BOHRIUM_API_KEY }}"
+ CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_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 657ab4ee5..0edf927db 100644
--- a/camel/configs/__init__.py
+++ b/camel/configs/__init__.py
@@ -16,6 +16,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 .crynux_config import CRYNUX_API_PARAMS, CrynuxConfig
from .deepseek_config import DEEPSEEK_API_PARAMS, DeepSeekConfig
from .gemini_config import Gemini_API_PARAMS, GeminiConfig
from .groq_config import GROQ_API_PARAMS, GroqConfig
@@ -112,4 +113,6 @@ __all__ = [
'LMStudioConfig',
'WatsonXConfig',
'WATSONX_API_PARAMS',
+ 'CrynuxConfig',
+ 'CRYNUX_API_PARAMS',
]
diff --git a/camel/configs/crynux_config.py b/camel/configs/crynux_config.py
new file mode 100644
index 000000000..7ddf49fe3
--- /dev/null
+++ b/camel/configs/crynux_config.py
@@ -0,0 +1,94 @@
+# ========= 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 Dict, Optional, Sequence, Type, Union
+
+from pydantic import BaseModel
+
+from camel.configs.base_config import BaseConfig
+
+
+class CrynuxConfig(BaseConfig):
+ r"""Defines the parameters for generating chat completions using the
+ OpenAI API.
+
+ 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`)
+ logit_bias (dict, optional): Modify the likelihood of specified tokens
+ appearing in the completion. Accepts a json object that maps tokens
+ (specified by their token ID in the tokenizer) to an associated
+ bias value from :obj:`-100` to :obj:`100`. Mathematically, the bias
+ is added to the logits generated by the model prior to sampling.
+ The exact effect will vary per model, but values between:obj:` -1`
+ and :obj:`1` should decrease or increase likelihood of selection;
+ values like :obj:`-100` or :obj:`100` should result in a ban or
+ exclusive selection of the relevant token. (default: :obj:`None`)
+ """
+
+ temperature: Optional[float] = None
+ top_p: Optional[float] = None
+ n: Optional[int] = None
+ stream: Optional[bool] = None
+ stop: Optional[Union[str, Sequence[str]]] = None
+ max_tokens: Optional[int] = None
+ presence_penalty: Optional[float] = None
+ response_format: Optional[Union[Type[BaseModel], Dict]] = None
+ frequency_penalty: Optional[float] = None
+ logit_bias: Optional[Dict] = None
+
+
+CRYNUX_API_PARAMS = {param for param in CrynuxConfig.model_fields.keys()}
diff --git a/camel/models/__init__.py b/camel/models/__init__.py
index 479c54215..e7152122e 100644
--- a/camel/models/__init__.py
+++ b/camel/models/__init__.py
@@ -18,6 +18,7 @@ from .azure_openai_model import AzureOpenAIModel
from .base_audio_model import BaseAudioModel
from .base_model import BaseModelBackend
from .cohere_model import CohereModel
+from .crynux_model import CrynuxModel
from .deepseek_model import DeepSeekModel
from .fish_audio_model import FishAudioModel
from .gemini_model import GeminiModel
@@ -96,4 +97,5 @@ __all__ = [
'VolcanoModel',
'LMStudioModel',
'WatsonXModel',
+ 'CrynuxModel',
]
diff --git a/camel/models/crynux_model.py b/camel/models/crynux_model.py
new file mode 100644
index 000000000..8dc52741c
--- /dev/null
+++ b/camel/models/crynux_model.py
@@ -0,0 +1,94 @@
+# ========= 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 CRYNUX_API_PARAMS, CrynuxConfig
+from camel.models.openai_compatible_model import OpenAICompatibleModel
+from camel.types import ModelType
+from camel.utils import (
+ BaseTokenCounter,
+ api_keys_required,
+)
+
+
+class CrynuxModel(OpenAICompatibleModel):
+ r"""Constructor for Crynux backend with OpenAI compatibility.
+
+ 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:`CrynuxConfig().as_dict()` will be used.
+ (default: :obj:`None`)
+ api_key (Optional[str], optional): The API key for authenticating with
+ the Crynux service. (default: :obj:`None`)
+ url (Optional[str], optional): The url to the Crynux service.
+ If not provided, "https://bridge.crynux.ai/v1/llm" will be used.
+ (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.
+ 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`)
+ """
+
+ @api_keys_required(
+ [
+ ("api_key", 'CRYNUX_API_KEY'),
+ ]
+ )
+ def __init__(
+ self,
+ model_type: Union[ModelType, str],
+ model_config_dict: Optional[Dict[str, Any]] = None,
+ api_key: Optional[str] = None,
+ url: Optional[str] = None,
+ token_counter: Optional[BaseTokenCounter] = None,
+ timeout: Optional[float] = None,
+ ) -> None:
+ if model_config_dict is None:
+ model_config_dict = CrynuxConfig().as_dict()
+ api_key = api_key or os.environ.get("CRYNUX_API_KEY")
+ url = url or os.environ.get(
+ "CRYNUX_API_BASE_URL", "https://bridge.crynux.ai/v1/llm"
+ )
+ 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,
+ )
+
+ def check_model_config(self):
+ r"""Check whether the model configuration contains any
+ unexpected arguments to Crynux API.
+
+ Raises:
+ ValueError: If the model configuration dictionary contains any
+ unexpected arguments to Crynux API.
+ """
+ for param in self.model_config_dict:
+ if param not in CRYNUX_API_PARAMS:
+ raise ValueError(
+ f"Unexpected argument `{param}` is "
+ "input into Crynux model backend."
+ )
diff --git a/camel/models/model_factory.py b/camel/models/model_factory.py
index 0739078e3..d55d27d37 100644
--- a/camel/models/model_factory.py
+++ b/camel/models/model_factory.py
@@ -20,6 +20,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.crynux_model import CrynuxModel
from camel.models.deepseek_model import DeepSeekModel
from camel.models.gemini_model import GeminiModel
from camel.models.groq_model import GroqModel
@@ -96,6 +97,7 @@ class ModelFactory:
ModelPlatformType.MODELSCOPE: ModelScopeModel,
ModelPlatformType.NOVITA: NovitaModel,
ModelPlatformType.WATSONX: WatsonXModel,
+ ModelPlatformType.CRYNUX: CrynuxModel,
}
@staticmethod
diff --git a/camel/types/enums.py b/camel/types/enums.py
index dbe40c3eb..1d4e139a9 100644
--- a/camel/types/enums.py
+++ b/camel/types/enums.py
@@ -384,6 +384,25 @@ class ModelType(UnifiedModelType, Enum):
)
WATSONX_MISTRAL_LARGE = "mistralai/mistral-large"
+ # Crynux models
+ CRYNUX_DEEPSEEK_R1_DISTILL_QWEN_1_5B = (
+ "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+ )
+ CRYNUX_DEEPSEEK_R1_DISTILL_QWEN_7B = (
+ "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
+ )
+ CRYNUX_DEEPSEEK_R1_DISTILL_LLAMA_8B = (
+ "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
+ )
+
+ CRYNUX_QWEN_3_4_B = "Qwen/Qwen3-4B"
+ CRYNUX_QWEN_3_8_B = "Qwen/Qwen3-8B"
+ CRYNUX_QWEN_2_5_7B = "Qwen/Qwen2.5-7B"
+ CRYNUX_QWEN_2_5_7B_INSTRUCT = "Qwen/Qwen2.5-7B-Instruct"
+
+ CRYNUX_NOUS_HERMES_3_LLAMA_3_1_8B = "NousResearch/Hermes-3-Llama-3.1-8B"
+ CRYNUX_NOUS_HERMES_3_LLAMA_3_2_3B = "NousResearch/Hermes-3-Llama-3.2-3B"
+
def __str__(self):
return self.value
@@ -891,6 +910,20 @@ class ModelType(UnifiedModelType, Enum):
ModelType.NOVITA_L31_70B_EURYALE_V2_2,
}
+ @property
+ def is_crynux(self) -> bool:
+ return self in {
+ ModelType.CRYNUX_DEEPSEEK_R1_DISTILL_QWEN_1_5B,
+ ModelType.CRYNUX_DEEPSEEK_R1_DISTILL_QWEN_7B,
+ ModelType.CRYNUX_DEEPSEEK_R1_DISTILL_LLAMA_8B,
+ ModelType.CRYNUX_QWEN_3_4_B,
+ ModelType.CRYNUX_QWEN_3_8_B,
+ ModelType.CRYNUX_QWEN_2_5_7B,
+ ModelType.CRYNUX_QWEN_2_5_7B_INSTRUCT,
+ ModelType.CRYNUX_NOUS_HERMES_3_LLAMA_3_1_8B,
+ ModelType.CRYNUX_NOUS_HERMES_3_LLAMA_3_2_3B,
+ }
+
@property
def is_aiml(self) -> bool:
return self in {
@@ -991,6 +1024,15 @@ class ModelType(UnifiedModelType, Enum):
ModelType.NOVITA_GLM_4_32B_0414,
ModelType.NOVITA_GLM_Z1_RUMINATION_32B_0414,
ModelType.NOVITA_QWEN_2_5_7B,
+ ModelType.CRYNUX_DEEPSEEK_R1_DISTILL_QWEN_1_5B,
+ ModelType.CRYNUX_DEEPSEEK_R1_DISTILL_QWEN_7B,
+ ModelType.CRYNUX_DEEPSEEK_R1_DISTILL_LLAMA_8B,
+ ModelType.CRYNUX_QWEN_3_4_B,
+ ModelType.CRYNUX_QWEN_3_8_B,
+ ModelType.CRYNUX_QWEN_2_5_7B,
+ ModelType.CRYNUX_QWEN_2_5_7B_INSTRUCT,
+ ModelType.CRYNUX_NOUS_HERMES_3_LLAMA_3_1_8B,
+ ModelType.CRYNUX_NOUS_HERMES_3_LLAMA_3_2_3B,
}:
return 32_000
elif self in {
@@ -1449,6 +1491,7 @@ class ModelPlatformType(Enum):
NETMIND = "netmind"
NOVITA = "novita"
WATSONX = "watsonx"
+ CRYNUX = "crynux"
@classmethod
def from_name(cls, name):
@@ -1624,6 +1667,11 @@ class ModelPlatformType(Enum):
r"""Returns whether this platform is WatsonX."""
return self is ModelPlatformType.WATSONX
+ @property
+ def is_crynux(self) -> bool:
+ r"""Returns whether this platform is Crynux."""
+ return self is ModelPlatformType.CRYNUX
+
class AudioModelType(Enum):
TTS_1 = "tts-1"
diff --git a/camel/types/unified_model_type.py b/camel/types/unified_model_type.py
index 411e431f5..3ecef7b23 100644
--- a/camel/types/unified_model_type.py
+++ b/camel/types/unified_model_type.py
@@ -163,6 +163,11 @@ class UnifiedModelType(str):
r"""Returns whether the model is a WatsonX served model."""
return True
+ @property
+ def is_crynux(self) -> bool:
+ r"""Returns whether the model is a Crynux served model."""
+ return True
+
@property
def support_native_structured_output(self) -> bool:
r"""Returns whether the model supports native structured output."""
diff --git a/docs/key_modules/models.md b/docs/key_modules/models.md
index 417cdf85d..97a526549 100644
--- a/docs/key_modules/models.md
+++ b/docs/key_modules/models.md
@@ -40,6 +40,7 @@ CAMEL supports a wide range of models, including [OpenAI’s GPT series](https:/
| **ModelScope** | [supported models](https://www.modelscope.cn/docs/model-service/API-Inference/intro) |
| **AWS Bedrock** | [supported models](https://us-west-2.console.aws.amazon.com/bedrock/home?region=us-west-2#/) |
| **IBM WatsonX** | [supported models](https://jp-tok.dataplatform.cloud.ibm.com/samples?context=wx&tab=foundation-model) |
+| **Crynux** | [supported models](https://docs.crynux.ai/application-development/how-to-run-llm-using-crynux-network/supported-models) |
## 3. How to Use Models via API Calls
diff --git a/examples/models/crynux_model_example.py b/examples/models/crynux_model_example.py
new file mode 100644
index 000000000..5f1ca8455
--- /dev/null
+++ b/examples/models/crynux_model_example.py
@@ -0,0 +1,54 @@
+# ========= 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.models import ModelFactory
+from camel.toolkits import SearchToolkit
+from camel.types import ModelPlatformType, ModelType
+
+"""
+please set the below os environment:
+export CRYNUX_API_KEY="your key"
+
+We offer an API key for testing (rate limit = 0.1):
+Rfx0SUNqUBovo5MZpArUbzIT3dJpm2JyEd7-6SgikW4=
+"""
+
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.CRYNUX,
+ model_type=ModelType.CRYNUX_QWEN_2_5_7B_INSTRUCT,
+ model_config_dict={"temperature": 0.0},
+)
+
+search_tool = SearchToolkit().search_duckduckgo
+
+agent = ChatAgent(model=model, tools=[search_tool])
+
+response_1 = agent.step("What is CAMEL-AI?")
+print(response_1.msgs[0].content)
+"""
+CAMEL-AI is a platform designed for building and researching
+ intelligent agents and multi-agent systems. This platform
+ is useful for data generation, world simulation, and task
+ automation. It provides tools, projects, and resources for
+ creating agentic applications using large language models
+ and other AI/ML technologies.
+"""
+
+response_2 = agent.step("What is the Github link to CAMEL framework?")
+print(response_2.msgs[0].content)
+"""
+The GitHub link to the CAMEL framework is:
+[https://github.com/camel-ai/camel](https://github.com/
+camel-ai/camel)
+"""
diff --git a/test/models/test_crynux_model.py b/test/models/test_crynux_model.py
new file mode 100644
index 000000000..e1d64e6bf
--- /dev/null
+++ b/test/models/test_crynux_model.py
@@ -0,0 +1,60 @@
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
+import re
+
+import pytest
+
+from camel.configs import CrynuxConfig
+from camel.models import CrynuxModel
+from camel.types import ModelType
+from camel.utils import OpenAITokenCounter
+
+
+ "model_type",
+ [
+ ModelType.CRYNUX_QWEN_2_5_7B_INSTRUCT,
+ ],
+)
+def test_crynux_model(model_type: ModelType):
+ model = CrynuxModel(model_type)
+ assert model.model_type == model_type
+ assert model.model_config_dict == CrynuxConfig().as_dict()
+ assert isinstance(model.token_counter, OpenAITokenCounter)
+ assert isinstance(model.model_type.value_for_tiktoken, str)
+ assert isinstance(model.model_type.token_limit, int)
+
+
+def test_crynux_model_unexpected_argument():
+ model_type = (ModelType.CRYNUX_QWEN_2_5_7B_INSTRUCT,)
+ model_config_dict = {"model_path": "qwen/qwen_2"}
+
+ with pytest.raises(
+ ValueError,
+ match=re.escape(
+ (
+ "Unexpected argument `model_path` is "
+ "input into Crynux model backend."
+ )
+ ),
+ ):
+ _ = CrynuxModel(model_type, model_config_dict)
+
+
+def test_crynux_model_stream_property():
+ model = CrynuxModel(ModelType.CRYNUX_QWEN_2_5_7B_INSTRUCT)
+ assert model.stream is False