camel.utils package#
Submodules#
camel.utils.async_func module#
- camel.utils.async_func.sync_funcs_to_async(funcs: list[OpenAIFunction]) list[OpenAIFunction] [source]#
Convert a list of Python synchronous functions to Python asynchronous functions.
- Parameters:
funcs (list[OpenAIFunction]) – List of Python synchronous functions in the
OpenAIFunction
format.- Returns:
- List of Python asynchronous functions
in the
OpenAIFunction
format.
- Return type:
list[OpenAIFunction]
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.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.constants module#
camel.utils.token_counting module#
- class camel.utils.token_counting.AnthropicTokenCounter(model_type: 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:
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.
- class camel.utils.token_counting.GeminiTokenCounter(model_type: 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:
Number of tokens in the messages.
- Return type:
int
- class camel.utils.token_counting.LiteLLMTokenCounter(model_type: str)[source]#
Bases:
object
- 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: 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: ModelType)[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
- class camel.utils.token_counting.OpenSourceTokenCounter(model_type: ModelType, model_path: str)[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
- 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
- camel.utils.token_counting.messages_to_prompt(messages: List[OpenAIMessage], model: ModelType) str [source]#
Parse the message list into a single prompt following model-specific formats.
- Parameters:
messages (List[OpenAIMessage]) – Message list with the chat history in OpenAI API format.
model (ModelType) – Model type for which messages will be parsed.
- Returns:
A single prompt summarizing all the messages.
- Return type:
str
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(model_type: 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:
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.
- class camel.utils.Constants[source]#
Bases:
object
- 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: 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:
Number of tokens in the messages.
- Return type:
int
- class camel.utils.LiteLLMTokenCounter(model_type: str)[source]#
Bases:
object
- 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: 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: ModelType)[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
- class camel.utils.OpenSourceTokenCounter(model_type: ModelType, model_path: str)[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
- 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