camel.utils package

Contents

camel.utils package#

Submodules#

camel.utils.async_func module#

camel.utils.async_func.sync_funcs_to_async(funcs: list[FunctionTool]) list[FunctionTool][source]#

Convert a list of Python synchronous functions to Python asynchronous functions.

Parameters:

funcs (list[FunctionTool]) – List of Python synchronous functions in the FunctionTool format.

Returns:

List of Python asynchronous functions

in the FunctionTool format.

Return type:

list[FunctionTool]

camel.utils.commons module#

class camel.utils.commons.AgentOpsMeta(name, bases, dct)[source]#

Bases: type

Metaclass that automatically decorates all callable attributes with the agentops_decorator, except for the ‘get_tools’ method.

Methods: __new__(cls, name, bases, dct):

Creates a new class with decorated methods.

camel.utils.commons.agentops_decorator(func)[source]#

Decorator that records the execution of a function if ToolEvent is available.

Parameters:

func (callable) – The function to be decorated.

Returns:

The wrapped function which records its execution details.

Return type:

callable

camel.utils.commons.api_keys_required(*required_keys: str) Callable[[F], F][source]#

A decorator to check if the required API keys are presented in the environment variables or as an instance attribute.

Parameters:

required_keys (str) – The required API keys to be checked.

Returns:

The original function with the added check

for required API keys.

Return type:

Callable[[F], F]

Raises:

ValueError – If any of the required API keys are missing in the environment variables and the instance attribute.

Example

@api_keys_required('API_KEY_1', 'API_KEY_2')
def some_api_function():
    # Function implementation...
camel.utils.commons.check_server_running(server_url: str) bool[source]#

Check whether the port refered by the URL to the server is open.

Parameters:

server_url (str) – The URL to the server running LLM inference service.

Returns:

Whether the port is open for packets (server is running).

Return type:

bool

camel.utils.commons.create_chunks(text: str, n: int) List[str][source]#

Returns successive n-sized chunks from provided text. Split a text into smaller chunks of size n”.

Parameters:
  • text (str) – The text to be split.

  • n (int) – The max length of a single chunk.

Returns:

A list of split texts.

Return type:

List[str]

camel.utils.commons.dependencies_required(*required_modules: str) Callable[[F], F][source]#

A decorator to ensure that specified Python modules are available before a function executes.

Parameters:

required_modules (str) – The required modules to be checked for availability.

Returns:

The original function with the added check for

required module dependencies.

Return type:

Callable[[F], F]

Raises:

ImportError – If any of the required modules are not available.

Example

@dependencies_required('numpy', 'pandas')
def data_processing_function():
    # Function implementation...
camel.utils.commons.download_tasks(task: TaskType, folder_path: str) None[source]#

Downloads task-related files from a specified URL and extracts them.

This function downloads a zip file containing tasks based on the specified task type from a predefined URL, saves it to folder_path, and then extracts the contents of the zip file into the same folder. After extraction, the zip file is deleted.

Parameters:
  • task (TaskType) – An enum representing the type of task to download.

  • folder_path (str) – The path of the folder where the zip file will be downloaded and extracted.

camel.utils.commons.func_string_to_callable(code: str)[source]#

Convert a function code string to a callable function object.

Parameters:

code (str) – The function code as a string.

Returns:

The callable function object extracted from the

code string.

Return type:

Callable[…, Any]

camel.utils.commons.get_first_int(string: str) int | None[source]#

Returns the first integer number found in the given string.

If no integer number is found, returns None.

Parameters:

string (str) – The input string.

Returns:

The first integer number found in the string, or None if

no integer number is found.

Return type:

int or None

camel.utils.commons.get_prompt_template_key_words(template: str) Set[str][source]#

Given a string template containing curly braces {}, return a set of the words inside the braces.

Parameters:

template (str) – A string containing curly braces.

Returns:

A list of the words inside the curly braces.

Return type:

List[str]

Example

>>> get_prompt_template_key_words('Hi, {name}! How are you {status}?')
{'name', 'status'}
camel.utils.commons.get_pydantic_major_version() int[source]#

Get the major version of Pydantic.

Returns:

The major version number of Pydantic if installed, otherwise 0.

Return type:

int

camel.utils.commons.get_pydantic_object_schema(pydantic_params: Type[BaseModel]) Dict[source]#

Get the JSON schema of a Pydantic model.

Parameters:

pydantic_params (Type[BaseModel]) – The Pydantic model class to retrieve the schema for.

Returns:

The JSON schema of the Pydantic model.

Return type:

dict

camel.utils.commons.get_system_information()[source]#

Gathers information about the operating system.

Returns:

A dictionary containing various pieces of OS information.

Return type:

dict

camel.utils.commons.get_task_list(task_response: str) List[str][source]#

Parse the response of the Agent and return task list.

Parameters:

task_response (str) – The string response of the Agent.

Returns:

A list of the string tasks.

Return type:

List[str]

camel.utils.commons.handle_http_error(response: Response) str[source]#

Handles the HTTP errors based on the status code of the response.

Parameters:

response (requests.Response) – The HTTP response from the API call.

Returns:

The error type, based on the status code.

Return type:

str

camel.utils.commons.is_docker_running() bool[source]#

Check if the Docker daemon is running.

Returns:

True if the Docker daemon is running, False otherwise.

Return type:

bool

camel.utils.commons.is_module_available(module_name: str) bool[source]#

Check if a module is available for import.

Parameters:

module_name (str) – The name of the module to check for availability.

Returns:

True if the module can be imported, False otherwise.

Return type:

bool

camel.utils.commons.json_to_function_code(json_obj: Dict) str[source]#

Generate a Python function code from a JSON schema.

Parameters:

json_obj (dict) – The JSON schema object containing properties and required fields, and json format is follow openai tools schema

Returns:

The generated Python function code as a string.

Return type:

str

camel.utils.commons.print_text_animated(text, delay: float = 0.02, end: str = '')[source]#

Prints the given text with an animated effect.

Parameters:
  • text (str) – The text to print.

  • delay (float, optional) – The delay between each character printed. (default: 0.02)

  • end (str, optional) – The end character to print after each character of text. (default: "")

camel.utils.commons.retry_request(func: Callable, retries: int = 3, delay: int = 1, *args: Any, **kwargs: Any) Any[source]#

Retries a function in case of any errors.

Parameters:
  • func (Callable) – The function to be retried.

  • retries (int) – Number of retry attempts. (default: 3)

  • delay (int) – Delay between retries in seconds. (default: 1)

  • *args – Arguments to pass to the function.

  • **kwargs – Keyword arguments to pass to the function.

Returns:

The result of the function call if successful.

Return type:

Any

Raises:

Exception – If all retry attempts fail.

camel.utils.commons.text_extract_from_web(url: str) str[source]#

Get the text information from given url.

Parameters:

url (str) – The website you want to search.

Returns:

All texts extract from the web.

Return type:

str

camel.utils.commons.to_pascal(snake: str) str[source]#

Convert a snake_case string to PascalCase.

Parameters:

snake (str) – The snake_case string to be converted.

Returns:

The converted PascalCase string.

Return type:

str

camel.utils.commons.track_agent(*args, **kwargs)[source]#

Mock track agent decorator for AgentOps.

camel.utils.constants module#

class camel.utils.constants.Constants[source]#

Bases: object

A class containing constants used in CAMEL.

DEFAULT_SIMILARITY_THRESHOLD = 0.7#
DEFAULT_TOP_K_RESULTS = 1#
FUNC_NAME_FOR_STRUCTURED_OUTPUT = 'return_json_response'#
VIDEO_DEFAULT_IMAGE_SIZE = 768#
VIDEO_DEFAULT_PLUG_PYAV = 'pyav'#
VIDEO_IMAGE_EXTRACTION_INTERVAL = 50#

camel.utils.token_counting module#

class camel.utils.token_counting.AnthropicTokenCounter[source]#

Bases: BaseTokenCounter

count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list using loaded tokenizer specific for this type of model.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Number of tokens in the messages.

Return type:

int

class camel.utils.token_counting.BaseTokenCounter[source]#

Bases: ABC

Base class for token counters of different kinds of models.

abstract count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Number of tokens in the messages.

Return type:

int

class camel.utils.token_counting.GeminiTokenCounter(model_type: UnifiedModelType)[source]#

Bases: BaseTokenCounter

count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list using loaded tokenizer specific for this type of model.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Number of tokens in the messages.

Return type:

int

class camel.utils.token_counting.LiteLLMTokenCounter(model_type: UnifiedModelType)[source]#

Bases: BaseTokenCounter

calculate_cost_from_response(response: dict) float[source]#

Calculate the cost of the given completion response.

Parameters:

response (dict) – The completion response from LiteLLM.

Returns:

The cost of the completion call in USD.

Return type:

float

property completion_cost#
count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list using the tokenizer specific to this type of model.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in LiteLLM API format.

Returns:

Number of tokens in the messages.

Return type:

int

property token_counter#
class camel.utils.token_counting.MistralTokenCounter(model_type: ~<unknown>.ModelType)[source]#

Bases: BaseTokenCounter

count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list using loaded tokenizer specific for this type of model.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Total number of tokens in the messages.

Return type:

int

class camel.utils.token_counting.OpenAITokenCounter(model: UnifiedModelType)[source]#

Bases: BaseTokenCounter

count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list with the help of package tiktoken.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Number of tokens in the messages.

Return type:

int

camel.utils.token_counting.get_model_encoding(value_for_tiktoken: str)[source]#

Get model encoding from tiktoken.

Parameters:

value_for_tiktoken – Model value for tiktoken.

Returns:

Model encoding.

Return type:

tiktoken.Encoding

Module contents#

class camel.utils.AgentOpsMeta(name, bases, dct)[source]#

Bases: type

Metaclass that automatically decorates all callable attributes with the agentops_decorator, except for the ‘get_tools’ method.

Methods: __new__(cls, name, bases, dct):

Creates a new class with decorated methods.

class camel.utils.AnthropicTokenCounter[source]#

Bases: BaseTokenCounter

count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list using loaded tokenizer specific for this type of model.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Number of tokens in the messages.

Return type:

int

class camel.utils.BaseTokenCounter[source]#

Bases: ABC

Base class for token counters of different kinds of models.

abstract count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Number of tokens in the messages.

Return type:

int

class camel.utils.Constants[source]#

Bases: object

A class containing constants used in CAMEL.

DEFAULT_SIMILARITY_THRESHOLD = 0.7#
DEFAULT_TOP_K_RESULTS = 1#
FUNC_NAME_FOR_STRUCTURED_OUTPUT = 'return_json_response'#
VIDEO_DEFAULT_IMAGE_SIZE = 768#
VIDEO_DEFAULT_PLUG_PYAV = 'pyav'#
VIDEO_IMAGE_EXTRACTION_INTERVAL = 50#
class camel.utils.GeminiTokenCounter(model_type: UnifiedModelType)[source]#

Bases: BaseTokenCounter

count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list using loaded tokenizer specific for this type of model.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Number of tokens in the messages.

Return type:

int

class camel.utils.LiteLLMTokenCounter(model_type: UnifiedModelType)[source]#

Bases: BaseTokenCounter

calculate_cost_from_response(response: dict) float[source]#

Calculate the cost of the given completion response.

Parameters:

response (dict) – The completion response from LiteLLM.

Returns:

The cost of the completion call in USD.

Return type:

float

property completion_cost#
count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list using the tokenizer specific to this type of model.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in LiteLLM API format.

Returns:

Number of tokens in the messages.

Return type:

int

property token_counter#
class camel.utils.MistralTokenCounter(model_type: ~<unknown>.ModelType)[source]#

Bases: BaseTokenCounter

count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list using loaded tokenizer specific for this type of model.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Total number of tokens in the messages.

Return type:

int

class camel.utils.OpenAITokenCounter(model: UnifiedModelType)[source]#

Bases: BaseTokenCounter

count_tokens_from_messages(messages: List[OpenAIMessage]) int[source]#

Count number of tokens in the provided message list with the help of package tiktoken.

Parameters:

messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.

Returns:

Number of tokens in the messages.

Return type:

int

camel.utils.agentops_decorator(func)[source]#

Decorator that records the execution of a function if ToolEvent is available.

Parameters:

func (callable) – The function to be decorated.

Returns:

The wrapped function which records its execution details.

Return type:

callable

camel.utils.api_keys_required(*required_keys: str) Callable[[F], F][source]#

A decorator to check if the required API keys are presented in the environment variables or as an instance attribute.

Parameters:

required_keys (str) – The required API keys to be checked.

Returns:

The original function with the added check

for required API keys.

Return type:

Callable[[F], F]

Raises:

ValueError – If any of the required API keys are missing in the environment variables and the instance attribute.

Example

@api_keys_required('API_KEY_1', 'API_KEY_2')
def some_api_function():
    # Function implementation...
camel.utils.check_server_running(server_url: str) bool[source]#

Check whether the port refered by the URL to the server is open.

Parameters:

server_url (str) – The URL to the server running LLM inference service.

Returns:

Whether the port is open for packets (server is running).

Return type:

bool

camel.utils.create_chunks(text: str, n: int) List[str][source]#

Returns successive n-sized chunks from provided text. Split a text into smaller chunks of size n”.

Parameters:
  • text (str) – The text to be split.

  • n (int) – The max length of a single chunk.

Returns:

A list of split texts.

Return type:

List[str]

camel.utils.dependencies_required(*required_modules: str) Callable[[F], F][source]#

A decorator to ensure that specified Python modules are available before a function executes.

Parameters:

required_modules (str) – The required modules to be checked for availability.

Returns:

The original function with the added check for

required module dependencies.

Return type:

Callable[[F], F]

Raises:

ImportError – If any of the required modules are not available.

Example

@dependencies_required('numpy', 'pandas')
def data_processing_function():
    # Function implementation...
camel.utils.download_tasks(task: TaskType, folder_path: str) None[source]#

Downloads task-related files from a specified URL and extracts them.

This function downloads a zip file containing tasks based on the specified task type from a predefined URL, saves it to folder_path, and then extracts the contents of the zip file into the same folder. After extraction, the zip file is deleted.

Parameters:
  • task (TaskType) – An enum representing the type of task to download.

  • folder_path (str) – The path of the folder where the zip file will be downloaded and extracted.

camel.utils.func_string_to_callable(code: str)[source]#

Convert a function code string to a callable function object.

Parameters:

code (str) – The function code as a string.

Returns:

The callable function object extracted from the

code string.

Return type:

Callable[…, Any]

camel.utils.get_first_int(string: str) int | None[source]#

Returns the first integer number found in the given string.

If no integer number is found, returns None.

Parameters:

string (str) – The input string.

Returns:

The first integer number found in the string, or None if

no integer number is found.

Return type:

int or None

camel.utils.get_model_encoding(value_for_tiktoken: str)[source]#

Get model encoding from tiktoken.

Parameters:

value_for_tiktoken – Model value for tiktoken.

Returns:

Model encoding.

Return type:

tiktoken.Encoding

camel.utils.get_prompt_template_key_words(template: str) Set[str][source]#

Given a string template containing curly braces {}, return a set of the words inside the braces.

Parameters:

template (str) – A string containing curly braces.

Returns:

A list of the words inside the curly braces.

Return type:

List[str]

Example

>>> get_prompt_template_key_words('Hi, {name}! How are you {status}?')
{'name', 'status'}
camel.utils.get_pydantic_major_version() int[source]#

Get the major version of Pydantic.

Returns:

The major version number of Pydantic if installed, otherwise 0.

Return type:

int

camel.utils.get_pydantic_object_schema(pydantic_params: Type[BaseModel]) Dict[source]#

Get the JSON schema of a Pydantic model.

Parameters:

pydantic_params (Type[BaseModel]) – The Pydantic model class to retrieve the schema for.

Returns:

The JSON schema of the Pydantic model.

Return type:

dict

camel.utils.get_system_information()[source]#

Gathers information about the operating system.

Returns:

A dictionary containing various pieces of OS information.

Return type:

dict

camel.utils.get_task_list(task_response: str) List[str][source]#

Parse the response of the Agent and return task list.

Parameters:

task_response (str) – The string response of the Agent.

Returns:

A list of the string tasks.

Return type:

List[str]

camel.utils.handle_http_error(response: Response) str[source]#

Handles the HTTP errors based on the status code of the response.

Parameters:

response (requests.Response) – The HTTP response from the API call.

Returns:

The error type, based on the status code.

Return type:

str

camel.utils.is_docker_running() bool[source]#

Check if the Docker daemon is running.

Returns:

True if the Docker daemon is running, False otherwise.

Return type:

bool

camel.utils.json_to_function_code(json_obj: Dict) str[source]#

Generate a Python function code from a JSON schema.

Parameters:

json_obj (dict) – The JSON schema object containing properties and required fields, and json format is follow openai tools schema

Returns:

The generated Python function code as a string.

Return type:

str

camel.utils.print_text_animated(text, delay: float = 0.02, end: str = '')[source]#

Prints the given text with an animated effect.

Parameters:
  • text (str) – The text to print.

  • delay (float, optional) – The delay between each character printed. (default: 0.02)

  • end (str, optional) – The end character to print after each character of text. (default: "")

camel.utils.text_extract_from_web(url: str) str[source]#

Get the text information from given url.

Parameters:

url (str) – The website you want to search.

Returns:

All texts extract from the web.

Return type:

str

camel.utils.to_pascal(snake: str) str[source]#

Convert a snake_case string to PascalCase.

Parameters:

snake (str) – The snake_case string to be converted.

Returns:

The converted PascalCase string.

Return type:

str

camel.utils.track_agent(*args, **kwargs)[source]#

Mock track agent decorator for AgentOps.