-
Notifications
You must be signed in to change notification settings - Fork 756
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: update aws_bedrock #1194
Open
Asher-hss
wants to merge
12
commits into
master
Choose a base branch
from
AWS_bedrock
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: update aws_bedrock #1194
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
cbe8324
update aws_bedrock
Asher-hss 58f3211
update
Asher-hss cafc88f
update
Asher-hss d3a63d0
Merge branch 'master' into AWS_bedrock
Asher-hss bad26be
update
Asher-hss 882f479
update
Asher-hss 220a330
update
Asher-hss a09a390
Merge branch 'master' into AWS_bedrock
Asher-hss 22168e5
update aws_bedrock
Asher-hss 4e8e931
update
Asher-hss 59e4021
update
Asher-hss b836155
update format
Asher-hss File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# ========= 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 typing import Optional, Union | ||
|
||
from camel.configs.base_config import BaseConfig | ||
|
||
|
||
class BedrockConfig(BaseConfig): | ||
r"""Defines the parameters for generating chat completions using Bedrock | ||
compatibility. | ||
|
||
Args: | ||
maxTokens (int, optional): The maximum number of tokens. | ||
temperatue (float, optional): Controls the randomness of the output. | ||
top_p (float, optional): Use nucleus sampling. | ||
tool_choice (Union[dict[str, str], str], optional): The tool choice. | ||
""" | ||
|
||
max_tokens: Optional[int] = 400 | ||
temperature: Optional[float] = 0.7 | ||
top_p: Optional[float] = 0.7 | ||
tool_choice: Optional[Union[dict[str, str], str]] = None | ||
|
||
|
||
BEDROCK_API_PARAMS = {param for param in BedrockConfig.model_fields.keys()} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
# ========= 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, List, Optional, Union | ||
|
||
from openai import OpenAI | ||
|
||
from camel.configs import BEDROCK_API_PARAMS, BedrockConfig | ||
from camel.messages import OpenAIMessage | ||
from camel.models.base_model import BaseModelBackend | ||
from camel.types import ChatCompletion, ModelType | ||
from camel.utils import ( | ||
BaseTokenCounter, | ||
OpenAITokenCounter, | ||
api_keys_required, | ||
) | ||
|
||
|
||
class AWSBedrockModel(BaseModelBackend): | ||
r"""AWS Bedrock API in a unified BaseModelBackend interface. | ||
|
||
Args: | ||
model_type (Union[ModelType, str]): Model for which a backend is | ||
created. | ||
model_config_dict (Dict[str, Any], optional): A dictionary | ||
that will be fed into:obj:`openai.ChatCompletion.create()`. | ||
If:obj:`None`, :obj:`BedrockConfig().as_dict()` will be used. | ||
(default: :obj:`None`) | ||
api_key (str, optional): The API key for authenticating with | ||
the AWS Bedrock service. (default: :obj:`None`) | ||
url (str, optional): The url to the AWS Bedrock service. | ||
token_counter (BaseTokenCounter, optional): Token counter to | ||
use for the model. If not provided, :obj:`OpenAITokenCounter( | ||
ModelType.GPT_4O_MINI)` will be used. | ||
(default: :obj:`None`) | ||
|
||
References: | ||
https://docs.aws.amazon.com/bedrock/latest/APIReference/welcome.html | ||
""" | ||
|
||
@api_keys_required( | ||
[ | ||
("url", "BEDROCK_API_BASE_URL"), | ||
] | ||
) | ||
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, | ||
) -> None: | ||
if model_config_dict is None: | ||
model_config_dict = BedrockConfig().as_dict() | ||
api_key = api_key or os.environ.get("BEDROCK_API_KEY") | ||
url = url or os.environ.get( | ||
"BEDROCK_API_BASE_URL", | ||
) | ||
super().__init__( | ||
model_type, model_config_dict, api_key, url, token_counter | ||
) | ||
self._client = OpenAI( | ||
timeout=180, | ||
max_retries=3, | ||
api_key=self._api_key, | ||
base_url=self._url, | ||
) | ||
|
||
def run(self, messages: List[OpenAIMessage]) -> ChatCompletion: | ||
r"""Runs the query to the backend model. | ||
|
||
Args: | ||
message (List[OpenAIMessage]): Message list with the chat history | ||
in OpenAI API format. | ||
|
||
Returns: | ||
ChatCompletion: The response object in OpenAI's format. | ||
""" | ||
response = self._client.chat.completions.create( | ||
messages=messages, | ||
model=self.model_type, | ||
**self.model_config_dict, | ||
) | ||
return response | ||
|
||
@property | ||
def token_counter(self) -> BaseTokenCounter: | ||
r"""Initialize the token counter for the model backend. | ||
|
||
Returns: | ||
BaseTokenCounter: The token counter following the model's | ||
tokenization style. | ||
""" | ||
if not self._token_counter: | ||
self._token_counter = OpenAITokenCounter(ModelType.GPT_4O_MINI) | ||
return self._token_counter | ||
|
||
def check_model_config(self): | ||
r"""Check whether the input model configuration contains unexpected | ||
arguments. | ||
|
||
Raises: | ||
ValueError: If the model configuration dictionary contains any | ||
unexpected argument for this model class. | ||
""" | ||
for param in self.model_config_dict: | ||
if param not in BEDROCK_API_PARAMS: | ||
raise ValueError( | ||
f"Invalid parameter '{param}' in model_config_dict. " | ||
f"Valid parameters are: {BEDROCK_API_PARAMS}" | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# ========= 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.types import ModelPlatformType | ||
|
||
model = ModelFactory.create( | ||
model_platform=ModelPlatformType.AWS_BEDROCK, | ||
model_type="meta.llama3-70b-instruct-v1:0", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add values in |
||
) | ||
|
||
camel_agent = ChatAgent(model=model) | ||
|
||
user_msg = """Say hi to CAMEL AI, one open-source community dedicated to the | ||
study of autonomous and communicative agents.""" | ||
|
||
response = camel_agent.step(user_msg) | ||
print(response.msgs[0].content) | ||
''' | ||
=============================================================================== | ||
Hi CAMEL AI community! It's great to see a dedicated group of individuals | ||
passionate about the study of autonomous and communicative agents. Your | ||
open-source community is a fantastic platform for collaboration, knowledge | ||
sharing, and innovation in this exciting field. I'm happy to interact with you | ||
and provide assistance on any topics related to autonomous agents, natural | ||
language processing, or artificial intelligence in general. Feel free to ask | ||
me any questions, share your projects, or discuss the latest advancements in | ||
the field. Let's explore the possibilities of autonomous and communicative | ||
agents together! | ||
=============================================================================== | ||
''' |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
400 token is quiet limited, could we set this to
None
?