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 AMD model platform support (#2985)

danielhua23b90c33ebf335
diff --git a/.github/workflows/build_package.yml b/.github/workflows/build_package.yml
index 6de3862de..48fd5a9f0 100644
--- a/.github/workflows/build_package.yml
+++ b/.github/workflows/build_package.yml
@@ -99,6 +99,7 @@ jobs:
AZURE_API_VERSION: "${{ secrets.AZURE_API_VERSION }}"
AZURE_DEPLOYMENT_NAME: "${{ secrets.AZURE_DEPLOYMENT_NAME }}"
AZURE_OPENAI_BASE_URL: "${{ secrets.AZURE_OPENAI_BASE_URL }}"
+ AMD_API_KEY: "${{ secrets.AMD_API_KEY }}"
MISTRAL_API_KEY: "${{ secrets.MISTRAL_API_KEY }}"
REKA_API_KEY: "${{ secrets.REKA_API_KEY }}"
NEO4J_URI: "${{ secrets.NEO4J_URI }}"
diff --git a/.github/workflows/pytest_package.yml b/.github/workflows/pytest_package.yml
index f61533916..e34bb3c9d 100644
--- a/.github/workflows/pytest_package.yml
+++ b/.github/workflows/pytest_package.yml
@@ -35,6 +35,7 @@ jobs:
ZHIPUAI_API_BASE_URL: "${{ secrets.ZHIPUAI_API_BASE_URL }}"
ZHIPUAI_API_KEY: "${{ secrets.ZHIPUAI_API_KEY }}"
HF_TOKEN: "${{ secrets.HF_TOKEN }}"
+ AMD_API_KEY: "${{ secrets.AMD_API_KEY }}"
AZURE_OPENAI_API_KEY: "${{ secrets.AZURE_OPENAI_API_KEY }}"
AZURE_API_VERSION: "${{ secrets.AZURE_API_VERSION }}"
AZURE_DEPLOYMENT_NAME: "${{ secrets.AZURE_DEPLOYMENT_NAME }}"
diff --git a/camel/configs/__init__.py b/camel/configs/__init__.py
index fbd4505f2..2e5f9fdcd 100644
--- a/camel/configs/__init__.py
+++ b/camel/configs/__init__.py
@@ -12,6 +12,7 @@
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
from .aiml_config import AIML_API_PARAMS, AIMLConfig
+from .amd_config import AMD_API_PARAMS, AMDConfig
from .anthropic_config import ANTHROPIC_API_PARAMS, AnthropicConfig
from .base_config import BaseConfig
from .bedrock_config import BEDROCK_API_PARAMS, BedrockConfig
@@ -111,6 +112,8 @@ __all__ = [
'SILICONFLOW_API_PARAMS',
'AIMLConfig',
'AIML_API_PARAMS',
+ 'AMDConfigs',
+ 'AMD_API_PARAMS',
'OpenRouterConfig',
'OPENROUTER_API_PARAMS',
'LMSTUDIO_API_PARAMS',
diff --git a/camel/configs/amd_config.py b/camel/configs/amd_config.py
new file mode 100644
index 000000000..5689aa1ea
--- /dev/null
+++ b/camel/configs/amd_config.py
@@ -0,0 +1,70 @@
+# ========= 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 List, Optional, Union
+
+from pydantic import Field
+
+from camel.configs.base_config import BaseConfig
+from camel.types import NotGiven
+
+
+class AMDConfig(BaseConfig):
+ r"""Configuration class for AMD API models.
+
+ This class defines the configuration parameters for AMD's language
+ models, including temperature, sampling parameters, and response format
+ settings.
+
+ Args:
+ stream (bool, optional): Whether to stream the response.
+ (default: :obj:`None`)
+ temperature (float, optional): Controls randomness in the response.
+ Higher values make output more random, lower values make it more
+ deterministic. Range: [0.0, 2.0]. (default: :obj:`None`)
+ top_p (float, optional): Controls diversity via nucleus sampling.
+ Range: [0.0, 1.0]. (default: :obj:`None`)
+ presence_penalty (float, optional): Penalizes new tokens based on
+ whether they appear in the text so far. Range: [-2.0, 2.0].
+ (default: :obj:`None`)
+ frequency_penalty (float, optional): Penalizes new tokens based on
+ their frequency in the text so far. Range: [-2.0, 2.0].
+ (default: :obj:`None`)
+ max_tokens (Union[int, NotGiven], optional): Maximum number of tokens
+ to generate. If not provided, model will use its default maximum.
+ (default: :obj:`None`)
+ seed (Optional[int], optional): Random seed for deterministic sampling.
+ (default: :obj:`None`)
+ tools (Optional[List[Dict]], optional): List of tools available to the
+ model. This includes tools such as a text editor, a calculator, or
+ a search engine. (default: :obj:`None`)
+ tool_choice (Optional[str], optional): Tool choice configuration.
+ (default: :obj:`None`)
+ stop (Optional[List[str]], optional): List of stop sequences.
+ (default: :obj:`None`)
+ """
+
+ stream: Optional[bool] = Field(default=None)
+ temperature: Optional[float] = Field(default=None)
+ top_p: Optional[float] = Field(default=None)
+ presence_penalty: Optional[float] = Field(default=None)
+ frequency_penalty: Optional[float] = Field(default=None)
+ max_tokens: Optional[Union[int, NotGiven]] = Field(default=None)
+ seed: Optional[int] = Field(default=None)
+ tool_choice: Optional[str] = Field(default=None)
+ stop: Optional[List[str]] = Field(default=None)
+
+
+AMD_API_PARAMS = {param for param in AMDConfig.model_fields.keys()}
diff --git a/camel/models/__init__.py b/camel/models/__init__.py
index ce39cc906..229c571ca 100644
--- a/camel/models/__init__.py
+++ b/camel/models/__init__.py
@@ -12,6 +12,7 @@
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
from .aiml_model import AIMLModel
+from .amd_model import AMDModel
from .anthropic_model import AnthropicModel
from .aws_bedrock_model import AWSBedrockModel
from .azure_openai_model import AzureOpenAIModel
@@ -62,6 +63,7 @@ __all__ = [
'OpenRouterModel',
'AzureOpenAIModel',
'AnthropicModel',
+ 'AMDModel',
'MistralModel',
'GroqModel',
'StubModel',
diff --git a/camel/models/amd_model.py b/camel/models/amd_model.py
new file mode 100644
index 000000000..fafbf3140
--- /dev/null
+++ b/camel/models/amd_model.py
@@ -0,0 +1,103 @@
+# ========= 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 AMD_API_PARAMS, AMDConfig
+from camel.models.openai_compatible_model import OpenAICompatibleModel
+from camel.types import ModelType
+from camel.utils import BaseTokenCounter, api_keys_required
+
+
+class AMDModel(OpenAICompatibleModel):
+ r"""AMD API in a unified OpenAICompatibleModel interface.
+
+ Args:
+ model_type (Union[ModelType, str]): Model for which a backend is
+ created, one of AMD series.
+ model_config_dict (Optional[Dict[str, Any]], optional): A dictionary
+ that will be fed into:obj:`openai.ChatCompletion.create()`. If
+ :obj:`None`, :obj:`AMDConfig().as_dict()` will be used.
+ (default: :obj:`None`)
+ api_key (Optional[str], optional): The API key for authenticating with
+ the AMD service. (default: :obj:`None`)
+ url (Optional[str], optional): The url to the AMD service.
+ (default: :obj:`None`)
+ token_counter (Optional[BaseTokenCounter], optional): Token counter to
+ use for the model. If not provided, :obj:`OpenAITokenCounter(
+ ModelType.GPT_4)` 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", "AMD_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,
+ max_retries: int = 3,
+ **kwargs: Any,
+ ) -> None:
+ if model_config_dict is None:
+ model_config_dict = AMDConfig().as_dict()
+ api_key = api_key or os.environ.get("AMD_API_KEY")
+ url = url or os.environ.get(
+ "AMD_API_BASE_URL", "https://llm-api.amd.com"
+ )
+ headers = {
+ 'Ocp-Apim-Subscription-Key': api_key
+ }
+ kwargs["default_headers"] = headers
+ 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,
+ )
+
+ def check_model_config(self):
+ r"""Check whether the model configuration contains any
+ unexpected arguments to AMD API.
+
+ Raises:
+ ValueError: If the model configuration dictionary contains any
+ unexpected arguments to AMD API.
+ """
+ for param in self.model_config_dict:
+ if param not in AMD_API_PARAMS:
+ raise ValueError(
+ f"Unexpected argument `{param}` is "
+ "input into AMD model backend."
+ )
diff --git a/camel/models/model_factory.py b/camel/models/model_factory.py
index 964f5a14f..387f9ea69 100644
--- a/camel/models/model_factory.py
+++ b/camel/models/model_factory.py
@@ -16,6 +16,7 @@ import os
from typing import ClassVar, Dict, Optional, Type, Union
from camel.models.aiml_model import AIMLModel
+from camel.models.amd_model import AMDModel
from camel.models.anthropic_model import AnthropicModel
from camel.models.aws_bedrock_model import AWSBedrockModel
from camel.models.azure_openai_model import AzureOpenAIModel
@@ -77,6 +78,7 @@ class ModelFactory:
ModelPlatformType.AWS_BEDROCK: AWSBedrockModel,
ModelPlatformType.NVIDIA: NvidiaModel,
ModelPlatformType.SILICONFLOW: SiliconFlowModel,
+ ModelPlatformType.AMD: AMDModel,
ModelPlatformType.AIML: AIMLModel,
ModelPlatformType.VOLCANO: VolcanoModel,
ModelPlatformType.NETMIND: NetmindModel,
diff --git a/camel/types/enums.py b/camel/types/enums.py
index d433623fd..36cf712da 100644
--- a/camel/types/enums.py
+++ b/camel/types/enums.py
@@ -64,6 +64,8 @@ class ModelType(UnifiedModelType, Enum):
AWS_CLAUDE_OPUS_4 = "anthropic.claude-opus-4-20250514-v1:0"
AWS_CLAUDE_OPUS_4_1 = "anthropic.claude-opus-4-1-20250805-v1:0"
+ AMD_GPT4 = "dvue-aoai-001-gpt-4.1"
+
GLM_4 = "glm-4"
GLM_4V = "glm-4v"
GLM_4V_FLASH = "glm-4v-flash"
@@ -515,7 +517,14 @@ class ModelType(UnifiedModelType, Enum):
ModelType.O4_MINI,
ModelType.O3,
}
-
+
+ @property
+ def is_amd(self) -> bool:
+ r"""Returns whether this type of models is a AMD model."""
+ return self in {
+ ModelType.AMD_GPT4,
+ }
+
@property
def is_aws_bedrock(self) -> bool:
r"""Returns whether this type of models is an AWS Bedrock model."""
@@ -1349,6 +1358,7 @@ class ModelType(UnifiedModelType, Enum):
ModelType.GLM_4_LONG,
ModelType.TOGETHER_LLAMA_4_MAVERICK,
ModelType.OPENROUTER_LLAMA_4_MAVERICK,
+ ModelType.AMD_GPT4,
ModelType.GPT_4_1,
ModelType.GPT_4_1_MINI,
ModelType.GPT_4_1_NANO,
@@ -1579,6 +1589,7 @@ class ModelPlatformType(Enum):
COHERE = "cohere"
YI = "lingyiwanwu"
QWEN = "tongyi-qianwen"
+ AMD = "amd"
NVIDIA = "nvidia"
DEEPSEEK = "deepseek"
PPIO = "ppio"
diff --git a/examples/models/amd_model_example.py b/examples/models/amd_model_example.py
new file mode 100644
index 000000000..9290fa8a7
--- /dev/null
+++ b/examples/models/amd_model_example.py
@@ -0,0 +1,147 @@
+# ========= 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 AMDConfig
+from camel.models import ModelFactory
+from camel.types import ModelPlatformType, ModelType
+
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.AMD,
+ model_type=ModelType.AMD_GPT4,
+ model_config_dict=AMDConfig(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 = """give me python code to develop a trading bot"""
+
+# Get response information
+response = camel_agent.step(user_msg)
+print(response.msgs[0].content)
+
+"""
+
+Certainly! Below is a **very basic example** of a trading bot using Python. This bot uses the `ccxt` library to connect to a cryptocurrency exchange (like Binance), fetches the latest price for a trading pair (e.g., BTC/USDT), and places a simple buy order if the price drops below a certain threshold. **This is for educational purposes only** and should not be used with real funds without significant improvements, error handling, and risk management.
+
+
+
+**Prerequisites:**
+
+
+
+1. Install `ccxt`:
+   ```bash
+   pip install ccxt
+   ```
+
+
+
+2. Get your API key and secret from your chosen exchange (e.g., Binance).
+
+
+
+---
+
+
+
+```python
+import ccxt
+import time
+
+
+
+# CONFIGURATION
+API_KEY = 'YOUR_API_KEY'
+API_SECRET = 'YOUR_API_SECRET'
+SYMBOL = 'BTC/USDT'
+BUY_PRICE = 30000  # Example threshold
+AMOUNT = 0.001     # Amount of BTC to buy
+
+
+
+# Initialize exchange
+exchange = ccxt.binance({
+    'apiKey': API_KEY,
+    'secret': API_SECRET,
+    'enableRateLimit': True,
+})
+
+
+
+def get_latest_price(symbol):
+    ticker = exchange.fetch_ticker(symbol)
+    return ticker['last']
+
+
+
+def place_buy_order(symbol, amount, price):
+    order = exchange.create_limit_buy_order(symbol, amount, price)
+    print(f"Buy order placed: {order}")
+    return order
+
+
+
+def main():
+    while True:
+        try:
+            price = get_latest_price(SYMBOL)
+            print(f"Current price for {SYMBOL}: {price}")
+
+
+
+            if price < BUY_PRICE:
+                print(f"Price below threshold! Placing buy order for {AMOUNT} {SYMBOL} at {price}")
+                place_buy_order(SYMBOL, AMOUNT, price)
+                break  # Stop after one buy for this example
+
+
+
+            time.sleep(10)  # Wait 10 seconds before checking again
+
+
+
+        except Exception as e:
+            print(f"Error: {e}")
+            time.sleep(10)
+
+
+
+if __name__ == "__main__":
+    main()
+```
+
+
+
+---
+
+
+
+**Important Notes:**
+
+
+
+- **Never share your API keys.**
+- This code does not include advanced error handling, logging, or risk management.
+- Test with a demo/sandbox account or very small amounts first.
+- You can expand this bot with strategies, stop-loss, take-profit, etc.
+- For real trading, always understand the risks and comply with local regulations.
+
+
+
+"""
diff --git a/test/models/test_amd_model.py b/test/models/test_amd_model.py
new file mode 100644
index 000000000..b38a2145f
--- /dev/null
+++ b/test/models/test_amd_model.py
@@ -0,0 +1,43 @@
+# ========= 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 AMDConfig
+from camel.models import AMDModel
+from camel.types import ModelType
+
+
+ "model_type",
+ [
+ ModelType.AMD_GPT4
+ ],
+)
+def test_amd_model(model_type: ModelType):
+ model = AMDModel(model_type)
+ assert model.model_type == model_type
+ assert model.model_config_dict == AMDConfig().as_dict()
+ assert isinstance(model.model_type.value_for_tiktoken, str)
+ assert isinstance(model.model_type.token_limit, int)
+
+
+def test_amd_model_unexpected_argument():
+ model_type = ModelType.AMD_GPT4
+
+ _ = AMDModel(model_type)