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

Enable OpenAI model streaming and fix `num_tokens_from_messages` (#184)

Zecheng Zhange92705ff927e
diff --git a/camel/agents/chat_agent.py b/camel/agents/chat_agent.py
index 0d166e7c1..926d115d2 100644
--- a/camel/agents/chat_agent.py
+++ b/camel/agents/chat_agent.py
@@ -11,8 +11,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
+from collections import defaultdict
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional
+from types import GeneratorType
+from typing import Any, Dict, List, Optional, Tuple
from tenacity import retry
from tenacity.stop import stop_after_attempt
@@ -23,7 +25,11 @@ from camel.configs import ChatGPTConfig
from camel.messages import BaseMessage
from camel.models import BaseModelBackend, ModelFactory
from camel.typing import ModelType, RoleType
-from camel.utils import num_tokens_from_messages, openai_api_key_required
+from camel.utils import (
+ get_model_encoding,
+ num_tokens_from_messages,
+ openai_api_key_required,
+)
@dataclass(frozen=True)
@@ -197,8 +203,8 @@ class ChatAgent(BaseAgent):
return self.stored_messages
def submit_message(self, message: BaseMessage) -> None:
- r"""Submits the externaly provided message as if it were an answer of
- the chat LLM from the backend. Currently the choise of the critic is
+ r"""Submits the externally provided message as if it were an answer of
+ the chat LLM from the backend. Currently, the choice of the critic is
submitted with this method.
Args:
@@ -223,10 +229,9 @@ class ChatAgent(BaseAgent):
for the self agent any incoming message is external.
Returns:
- ChatAgentResponse: A struct
- containing the output messages, a boolean indicating whether
- the chat session has terminated, and information about the chat
- session.
+ ChatAgentResponse: A struct containing the output messages,
+ a boolean indicating whether the chat session has terminated,
+ and information about the chat session.
"""
messages = self.update_messages('user', input_message)
if self.message_window_size is not None and len(
@@ -241,21 +246,17 @@ class ChatAgent(BaseAgent):
if num_tokens < self.model_token_limit:
response = self.model_backend.run(openai_messages)
- if not isinstance(response, dict):
- raise RuntimeError("OpenAI returned unexpected struct")
- output_messages = [
- BaseMessage(role_name=self.role_name, role_type=self.role_type,
- meta_dict=dict(),
- content=choice["message"]['content'])
- for choice in response["choices"]
- ]
+ self.validate_model_response(response)
+ if not self.model_backend.stream:
+ output_messages, finish_reasons, usage_dict, response_id = \
+ self.handle_batch_response(response)
+ else:
+ output_messages, finish_reasons, usage_dict, response_id = \
+ self.handle_stream_response(response, num_tokens)
info = self.get_info(
- response["id"],
- response["usage"],
- [
- str(choice["finish_reason"])
- for choice in response["choices"]
- ],
+ response_id,
+ usage_dict,
+ finish_reasons,
num_tokens,
)
else:
@@ -271,6 +272,104 @@ class ChatAgent(BaseAgent):
return ChatAgentResponse(output_messages, self.terminated, info)
+ def validate_model_response(self, response: Any):
+ if not self.model_backend.stream:
+ if not isinstance(response, dict):
+ raise RuntimeError("OpenAI returned unexpected batch struct")
+ else:
+ if not isinstance(response, GeneratorType):
+ raise RuntimeError("OpenAI returned unexpected stream struct")
+
+ def handle_batch_response(
+ self, response: Dict[str, Any]
+ ) -> Tuple[List[BaseMessage], List[str], Dict[str, int], str]:
+ r"""
+
+ Args:
+ response (dict): Model response.
+
+ Returns:
+ tuple: A tuple of list of output `ChatMessage`, list of
+ finish reasons, usage dictionary, and response id.
+ """
+ output_messages: List[BaseMessage] = []
+ for choice in response["choices"]:
+ chat_message = BaseMessage(role_name=self.role_name,
+ role_type=self.role_type,
+ meta_dict=dict(),
+ content=choice["message"]['content'])
+ output_messages.append(chat_message)
+ finish_reasons = [
+ str(choice["finish_reason"]) for choice in response["choices"]
+ ]
+ return output_messages, finish_reasons, dict(
+ response["usage"]), response["id"]
+
+ def handle_stream_response(
+ self,
+ response: Any,
+ prompt_tokens: int,
+ ) -> Tuple[List[BaseMessage], List[str], Dict[str, int], str]:
+ r"""
+
+ Args:
+ response (dict): Model response.
+ prompt_tokens (int): Number of input prompt tokens.
+
+ Returns:
+ tuple: A tuple of list of output `ChatMessage`, list of
+ finish reasons, usage dictionary, and response id.
+ """
+ content_dict = defaultdict(lambda: "")
+ finish_reasons = defaultdict(lambda: "")
+ output_messages: List[BaseMessage] = []
+ response_id: str = ""
+ # All choices in one response share one role
+ role: str = ""
+ for chunk in response:
+ response_id = chunk["id"]
+ for choice in chunk["choices"]:
+ index = choice["index"]
+ delta = choice["delta"]
+ if len(delta) != 0:
+ # When response has not been stopped
+ # Notice that only the first chunk has the "role"
+ role = delta.get("role", role)
+ delta_content = delta.get("content", "")
+ content_dict[index] += delta_content
+ else:
+ finish_reasons[index] = choice["finish_reason"]
+ chat_message = BaseMessage(role_name=self.role_name,
+ role_type=self.role_type,
+ meta_dict=dict(),
+ content=content_dict[index])
+ output_messages.append(chat_message)
+ finish_reasons = [
+ finish_reasons[i] for i in range(len(finish_reasons))
+ ]
+ usage_dict = self.get_usage_dict(output_messages, prompt_tokens)
+ return output_messages, finish_reasons, usage_dict, response_id
+
+ def get_usage_dict(self, output_messages: List[BaseMessage],
+ prompt_tokens: int) -> Dict[str, int]:
+ r"""Get usage dictionary when using the stream mode.
+
+ Args:
+ output_messages (list): List of output messages.
+ prompt_tokens (int): Number of input prompt tokens.
+
+ Returns:
+ dict: Usage dictionary.
+ """
+ encoding = get_model_encoding(self.model.value_for_tiktoken)
+ completion_tokens = 0
+ for message in output_messages:
+ completion_tokens += len(encoding.encode(message.content))
+ usage_dict = dict(completion_tokens=completion_tokens,
+ prompt_tokens=prompt_tokens,
+ total_tokens=completion_tokens + prompt_tokens)
+ return usage_dict
+
def __repr__(self) -> str:
r"""Returns a string representation of the :obj:`ChatAgent`.
diff --git a/camel/models/base_model.py b/camel/models/base_model.py
index 3902b2a4c..8d058d24c 100644
--- a/camel/models/base_model.py
+++ b/camel/models/base_model.py
@@ -56,3 +56,12 @@ class BaseModelBackend(ABC):
int: The maximum token limit for the given model.
"""
return self.model_type.token_limit
+
+ @property
+ def stream(self) -> bool:
+ r"""Returns whether the model is in stream mode,
+ which sends partial results each time.
+ Returns:
+ bool: Whether the model is in stream mode.
+ """
+ return False
diff --git a/camel/models/openai_model.py b/camel/models/openai_model.py
index d979a43cd..6898db184 100644
--- a/camel/models/openai_model.py
+++ b/camel/models/openai_model.py
@@ -11,6 +11,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
+from types import GeneratorType
from typing import Any, Dict, List
from camel.messages import OpenAIMessage
@@ -48,6 +49,19 @@ class OpenAIModel(BaseModelBackend):
response = openai.ChatCompletion.create(messages=messages_openai,
model=self.model_type.value,
**self.model_config_dict)
- if not isinstance(response, Dict):
- raise RuntimeError("Unexpected return from OpenAI API")
+ if not self.stream:
+ if not isinstance(response, Dict):
+ raise RuntimeError("Unexpected batch return from OpenAI API")
+ else:
+ if not isinstance(response, GeneratorType):
+ raise RuntimeError("Unexpected stream return from OpenAI API")
return response
+
+ @property
+ def stream(self) -> bool:
+ r"""Returns whether the model is in stream mode,
+ which sends partial results each time.
+ Returns:
+ bool: Whether the model is in stream mode.
+ """
+ return self.model_config_dict.get('stream', False)
diff --git a/camel/utils.py b/camel/utils.py
index b726b1ffb..169fde3a9 100644
--- a/camel/utils.py
+++ b/camel/utils.py
@@ -27,6 +27,23 @@ from camel.typing import ModelType, TaskType
F = TypeVar('F', bound=Callable[..., Any])
+def get_model_encoding(value_for_tiktoken: str):
+ r"""Get model encoding from tiktoken.
+
+ Args:
+ value_for_tiktoken: Model value for tiktoken.
+
+ Returns:
+ tiktoken.Encoding: Model encoding.
+ """
+ try:
+ encoding = tiktoken.encoding_for_model(value_for_tiktoken)
+ except KeyError:
+ print("Model not found. Using cl100k_base encoding.")
+ encoding = tiktoken.get_encoding("cl100k_base")
+ return encoding
+
+
def count_tokens_openai_chat_models(
messages: List[OpenAIMessage],
encoding: tiktoken.Encoding,
@@ -39,6 +56,10 @@ def count_tokens_openai_chat_models(
Args:
messages (List[OpenAIMessage]): The list of messages.
encoding (tiktoken.Encoding): The encoding method to use.
+ tokens_per_message (int): Number of tokens to be added
+ to each message.
+ tokens_per_name (int): Number of tokens to be added if
+ name existed in the message.
Returns:
int: The number of tokens required.
@@ -48,7 +69,7 @@ def count_tokens_openai_chat_models(
num_tokens += tokens_per_message
for key, value in message.items():
num_tokens += len(encoding.encode(value))
- if key == "name": # if there's a name, the role is omitted
+ if key == "name":
num_tokens += tokens_per_name
num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>
return num_tokens
@@ -76,32 +97,35 @@ def num_tokens_from_messages(
- https://platform.openai.com/docs/models/gpt-4
- https://platform.openai.com/docs/models/gpt-3-5
"""
- try:
- value_for_tiktoken = model.value_for_tiktoken
- encoding = tiktoken.encoding_for_model(value_for_tiktoken)
- except KeyError:
- encoding = tiktoken.get_encoding("cl100k_base")
+ return _num_tokens_from_messages(messages, model.value_for_tiktoken)
- if model.value_for_tiktoken.startswith("gpt-3.5-turbo"):
+
+# flake8: noqa :E501
+def _num_tokens_from_messages(messages: List[OpenAIMessage], model: str):
+ r"""Return the number of tokens used by a list of messages.
+
+ References:
+ - https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
+ """
+ if model in {
+ "gpt-3.5-turbo-0613",
+ "gpt-3.5-turbo-16k-0613",
+ "gpt-4-0314",
+ "gpt-4-32k-0314",
+ "gpt-4-0613",
+ "gpt-4-32k-0613",
+ }:
+ tokens_per_message = 3
+ tokens_per_name = 1
+ elif model == "gpt-3.5-turbo-0301":
# Every message follows <|start|>{role/name}\n{content}<|end|>\n
tokens_per_message = 4
# If there's a name, the role is omitted
tokens_per_name = -1
- return count_tokens_openai_chat_models(
- messages,
- encoding,
- tokens_per_message,
- tokens_per_name,
- )
- elif model.value_for_tiktoken.startswith("gpt-4"):
- tokens_per_message = 3
- tokens_per_name = 1
- return count_tokens_openai_chat_models(
- messages,
- encoding,
- tokens_per_message,
- tokens_per_name,
- )
+ elif "gpt-3.5-turbo" in model:
+ return _num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")
+ elif "gpt-4" in model:
+ return _num_tokens_from_messages(messages, model="gpt-4-0613")
else:
raise NotImplementedError(
f"`num_tokens_from_messages`` is not presently implemented "
@@ -111,6 +135,9 @@ def num_tokens_from_messages(
f"See https://platform.openai.com/docs/models/gpt-4"
f"or https://platform.openai.com/docs/models/gpt-3-5"
f"for information about openai chat models.")
+ encoding = get_model_encoding(model)
+ return count_tokens_openai_chat_models(messages, encoding,
+ tokens_per_message, tokens_per_name)
def openai_api_key_required(func: F) -> F:
@@ -150,8 +177,8 @@ def print_text_animated(text, delay: float = 0.02, end: str = ""):
text (str): The text to print.
delay (float, optional): The delay between each character printed.
(default: :obj:`0.02`)
- end (str, optional): The end character to print after the text.
- (default: :obj:`""`)
+ end (str, optional): The end character to print after each
+ character of text. (default: :obj:`""`)
"""
for char in text:
print(char, end=end, flush=True)
diff --git a/examples/translation/translator.py b/examples/translation/translator.py
index fe1b83aac..5da003326 100644
--- a/examples/translation/translator.py
+++ b/examples/translation/translator.py
@@ -11,26 +11,61 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
+import argparse
import codecs
import json
import multiprocessing
import os
+import os.path as osp
+import warnings
from camel.agents import ChatAgent
+from camel.configs import ChatGPTConfig
from camel.generators import SystemMessageGenerator
from camel.messages import BaseMessage
from camel.typing import ModelType, RoleType, TaskType
-
-def translate_content(directory_path: str, file_path: str,
+warnings.filterwarnings("ignore")
+
+language_list = [
+ "arabic", "chinese", "french", "german", "hindi", "italian", "japanese",
+ "korean", "russian", "spanish"
+]
+
+parser = argparse.ArgumentParser(description='Arguments for translation.')
+parser.add_argument('--directory_path', type=str,
+ help='Directory that contains original json files',
+ default='../camel_data/ai_society')
+parser.add_argument('--save_directory_path', type=str,
+ help='Directory to save translated files',
+ default='../camel_data/ai_society_translated')
+parser.add_argument('--single', action='store_true',
+ help='Run translator in a non-parallel way.')
+parser.add_argument('--stream', action='store_true',
+ help='Set OpenAI GPT model with the stream mode.')
+parser.add_argument(
+ '--language', type=str, help='Language you want to translated to. '
+ 'Notice that this is not used in the parallel mode, '
+ 'which uses SLURM_ARRAY_TASK_ID to indicate the '
+ 'language to be translated.', choices=language_list, default='arabic')
+
+
+def translate_content(args: argparse.Namespace, file_path: str,
language: str) -> None:
- # File_path of the .json file to translate we extract the name for saving
- file_name = file_path.split("/")[-1].split(".json")[0]
+ # Extract file name from the .json file path to be translated
+ file_name = osp.splitext(osp.basename(file_path))[0]
+
+ if not osp.exists(args.save_directory_path):
+ os.makedirs(args.save_directory_path)
- # Check that file_name.json does not exist in the target directory
- save_path = f"{directory_path}_translated/{language}/{file_name}.json"
- if os.path.exists(save_path):
+ save_lang_director_path = osp.join(args.save_directory_path, language)
+ if not osp.exists(save_lang_director_path):
+ os.makedirs(save_lang_director_path)
+
+ # Check that file_name.json does not exist in the save directory
+ save_path = osp.join(save_lang_director_path, f'{file_name}.json')
+ if osp.exists(save_path):
return
# Load the json file
@@ -50,7 +85,16 @@ def translate_content(directory_path: str, file_path: str,
meta_dict=dict(language=language.capitalize()),
role_tuple=('Language Translator', RoleType.ASSISTANT))
- assistant_agent = ChatAgent(assistant_sys_msg, ModelType.GPT_3_5_TURBO)
+ if not args.stream:
+ model_config = ChatGPTConfig(stream=False)
+ else:
+ model_config = ChatGPTConfig(stream=True)
+
+ assistant_agent = ChatAgent(
+ system_message=assistant_sys_msg,
+ model=ModelType.GPT_3_5_TURBO,
+ model_config=model_config,
+ )
user_msg = BaseMessage.make_user_message(
role_name="Language Translator", content=msg_i_content)
@@ -64,41 +108,46 @@ def translate_content(directory_path: str, file_path: str,
json.dump(json_data, f, ensure_ascii=False, indent=4)
-def main(directory_path: str) -> None:
-
- # List of languages to translate to
- language_list = [
- "arabic", "chinese", "french", "german", "hindi", "italian",
- "japanese", "korean", "russian", "spanish"
- ]
-
- # Get the language to translate based on Slurm array index
- try:
- language_index = int(os.environ["SLURM_ARRAY_TASK_ID"])
- except KeyError:
- print("SLURM_ARRAY_TASK_ID not found. Defaulting to 0 (i.e Arabic)")
- # Default to Arabic, you can change to any other language
- language_index = 0
-
- language = language_list[language_index]
+def main(args: argparse.Namespace) -> None:
+ if not args.single:
+ # Get the language to translate based on Slurm array index
+ slum_id_env = "SLURM_ARRAY_TASK_ID"
+ try:
+ language_index = int(os.environ[slum_id_env])
+ except KeyError:
+ print(f"{slum_id_env} not found. Defaulting to 0 (i.e Arabic)")
+ # Default to Arabic, you can change to any other language
+ language_index = 0
+ # List of languages to translate to
+ language_list = [
+ "arabic", "chinese", "french", "german", "hindi", "italian",
+ "japanese", "korean", "russian", "spanish"
+ ]
+ language = language_list[language_index]
+ else:
+ language = args.language
# Get list of all .json files paths
json_file_paths = []
- for filename in os.listdir(directory_path):
+ for filename in os.listdir(args.directory_path):
if filename.endswith(".json"):
- file_path = os.path.join(directory_path, filename)
+ file_path = osp.join(args.directory_path, filename)
json_file_paths.append(file_path)
- pool = multiprocessing.Pool()
-
- # Apply parallel translation to all .json files
- for file_path in json_file_paths:
- pool.apply_async(translate_content,
- args=(directory_path, file_path, language))
- pool.close()
- pool.join()
+ if not args.single:
+ pool = multiprocessing.Pool()
+ # Apply parallel translation to all .json files
+ for file_path in json_file_paths:
+ pool.apply_async(translate_content,
+ args=(args, file_path, language))
+ pool.close()
+ pool.join()
+ else:
+ for file_path in json_file_paths:
+ translate_content(args, file_path, language)
if __name__ == "__main__":
- main(directory_path="./camel_data/ai_society")
+ args = parser.parse_args()
+ main(args=args)
diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.py
index 90bd7e5c5..5905e0abf 100644
--- a/test/agents/test_chat_agent.py
+++ b/test/agents/test_chat_agent.py
@@ -28,7 +28,6 @@ parametrize = pytest.mark.parametrize('model', [
@parametrize
def test_chat_agent(model: ModelType):
-
model_config = ChatGPTConfig()
system_msg = SystemMessageGenerator(
task_type=TaskType.AI_SOCIETY).from_dict(
@@ -83,6 +82,34 @@ def test_chat_agent_multiple_return_messages(n):
assert len(assistant_response.msgs) == n
+def test_chat_agent_batch_stream_same_output():
+ system_msg = BaseMessage("Assistant", RoleType.ASSISTANT, meta_dict=None,
+ content="You are a helpful assistant.")
+ user_msg = BaseMessage(role_name="User", role_type=RoleType.USER,
+ meta_dict=dict(), content="Tell me a joke.")
+ batch_model_config = ChatGPTConfig(temperature=0, n=2, stream=False)
+ batch_assistant = ChatAgent(system_msg, model_config=batch_model_config)
+ batch_assistant.reset()
+ batch_assistant_response = batch_assistant.step(user_msg)
+
+ stream_model_config = ChatGPTConfig(temperature=0, n=2, stream=True)
+ stream_assistant = ChatAgent(system_msg, model_config=stream_model_config)
+ stream_assistant.reset()
+ stream_assistant_response = stream_assistant.step(user_msg)
+
+ for i in range(len(batch_assistant_response.msgs)):
+ batch_msg_content = batch_assistant_response.msgs[i].content
+ stream_msg_content = stream_assistant_response.msgs[i].content
+ assert batch_msg_content == stream_msg_content
+
+ batch_usage = batch_assistant_response.info["usage"]
+ stream_usage = stream_assistant_response.info["usage"]
+ for key in batch_usage:
+ assert key in stream_usage
+ assert stream_usage[key] == batch_usage[key]
+
+
@pytest.mark.model_backend
def test_set_output_language():
system_message = BaseMessage(role_name="assistant",
@@ -101,7 +128,7 @@ def test_set_output_language():
# Verify that the system message is updated with the new output language
updated_system_message = BaseMessage(
- role_name="assistant", role_type="assistant", meta_dict=None,
+ role_name="assistant", role_type=RoleType.ASSISTANT, meta_dict=None,
content="You are a help assistant."
"\nRegardless of the input language, you must output text in Arabic.")
assert agent.system_message.content == updated_system_message.content
diff --git a/test/messages/test_message_base.py b/test/messages/test_message_base.py
index 5711d46d4..d0bdf5f12 100644
--- a/test/messages/test_message_base.py
+++ b/test/messages/test_message_base.py
@@ -50,7 +50,7 @@ def test_base_message_contains_operator(base_message: BaseMessage):
def test_base_message_token_len(base_message: BaseMessage):
token_len = base_message.token_len("user")
assert isinstance(token_len, int)
- assert token_len == 10
+ assert token_len == 9
def test_extract_text_and_code_prompts():