camel.toolkits package#
Submodules#
camel.toolkits.base module#
- class camel.toolkits.base.BaseToolkit[source]#
Bases:
object
Base class for toolkits.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
camel.toolkits.code_execution module#
- class camel.toolkits.code_execution.CodeExecutionToolkit(sandbox: Literal['internal_python', 'jupyter', 'docker', 'subprocess', 'e2b'] = 'internal_python', verbose: bool = False, unsafe_mode: bool = False, import_white_list: List[str] | None = None, require_confirm: bool = False)[source]#
Bases:
BaseToolkit
A tookit for code execution.
- Parameters:
sandbox (str) – The environment type used to execute code.
verbose (bool) – Whether to print the output of the code execution. (default:
False
)unsafe_mode (bool) – If True, the interpreter runs the code by eval() without any security check. (default:
False
)import_white_list (Optional[List[str]]) – A list of allowed imports. (default:
None
)require_confirm (bool) – Whether to require confirmation before executing code. (default:
False
)
- execute_code(code: str) str [source]#
Execute a given code snippet.
- Parameters:
code (str) – The input code to the Code Interpreter tool call.
- Returns:
The text output from the Code Interpreter tool call.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
camel.toolkits.dalle_toolkit module#
- class camel.toolkits.dalle_toolkit.DalleToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for image generation using OpenAI’s DALL-E model.
- base64_to_image(base64_string: str) Image | None [source]#
Converts a base64 encoded string into a PIL Image object.
- Parameters:
base64_string (str) – The base64 encoded string of the image.
- Returns:
- The PIL Image object or None if conversion
fails.
- Return type:
Optional[Image.Image]
- get_dalle_img(prompt: str, image_dir: str = 'img') str [source]#
- Generate an image using OpenAI’s DALL-E model.
The generated image is saved to the specified directory.
- Parameters:
prompt (str) – The text prompt based on which the image is generated.
image_dir (str) – The directory to save the generated image. Defaults to ‘img’.
- Returns:
The path to the saved image.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- image_path_to_base64(image_path: str) str [source]#
Converts the file path of an image to a Base64 encoded string.
- Parameters:
image_path (str) – The path to the image file.
- Returns:
- A Base64 encoded string representing the content of the image
file.
- Return type:
str
- image_to_base64(image: Image) str [source]#
Converts an image into a base64-encoded string.
This function takes an image object as input, encodes the image into a PNG format base64 string, and returns it. If the encoding process encounters an error, it prints the error message and returns None.
- Parameters:
image – The image object to be encoded, supports any image format that can be saved in PNG format.
- Returns:
A base64-encoded string of the image.
- Return type:
str
camel.toolkits.github_toolkit module#
- class camel.toolkits.github_toolkit.GithubToolkit(repo_name: str, access_token: str | None = None)[source]#
Bases:
BaseToolkit
A class representing a toolkit for interacting with GitHub repositories.
- This class provides methods for retrieving open issues, retrieving
specific issues, and creating pull requests in a GitHub repository.
- Parameters:
repo_name (str) – The name of the GitHub repository.
access_token (str, optional) – The access token to authenticate with GitHub. If not provided, it will be obtained using the get_github_access_token method.
- create_pull_request(file_path: str, new_content: str, pr_title: str, body: str, branch_name: str) str [source]#
Creates a pull request.
This function creates a pull request in specified repository, which updates a file in the specific path with new content. The pull request description contains information about the issue title and number.
- Parameters:
file_path (str) – The path of the file to be updated in the repository.
new_content (str) – The specified new content of the specified file.
pr_title (str) – The title of the issue that is solved by this pull request.
body (str) – The commit message for the pull request.
branch_name (str) – The name of the branch to create and submit the pull request from.
- Returns:
- A formatted report of whether the pull request was created
successfully or not.
- Return type:
str
- get_all_file_paths(path: str = '') List[str] [source]#
Recursively retrieves all file paths in the GitHub repository.
- Parameters:
path (str) – The repository path to start the traversal from. empty string means starts from the root directory. (default: :obj: “”)
- Returns:
- A list of file paths within the specified directory
structure.
- Return type:
List[str]
- get_github_access_token() str [source]#
Retrieve the GitHub access token from environment variables.
- Returns:
A string containing the GitHub access token.
- Return type:
str
- Raises:
ValueError – If the API key or secret is not found in the environment variables.
- get_issue_content(issue_number: int) str [source]#
Retrieves the content of a specific issue by its number.
- Parameters:
issue_number (int) – The number of the issue to retrieve.
- Returns:
issues content details.
- Return type:
str
- get_issue_list(state: Literal['open', 'closed', 'all'] = 'all') List[Dict[str, object]] [source]#
Retrieves all issues from the GitHub repository.
- Parameters:
state (Literal["open", "closed", "all"]) – The state of pull requests to retrieve. (default: :obj: all) Options are: - “open”: Retrieve only open pull requests. - “closed”: Retrieve only closed pull requests. - “all”: Retrieve all pull requests, regardless of state.
- Returns:
- A list of dictionaries where each
dictionary contains the issue number and title.
- Return type:
List[Dict[str, object]]
- get_pull_request_code(pr_number: int) List[Dict[str, str]] [source]#
Retrieves the code changes of a specific pull request.
- Parameters:
pr_number (int) – The number of the pull request to retrieve.
- Returns:
- A list of dictionaries where each dictionary
contains the file name and the corresponding code changes (patch).
- Return type:
List[Dict[str, str]]
- get_pull_request_comments(pr_number: int) List[Dict[str, str]] [source]#
Retrieves the comments from a specific pull request.
- Parameters:
pr_number (int) – The number of the pull request to retrieve.
- Returns:
- A list of dictionaries where each dictionary
contains the user ID and the comment body.
- Return type:
List[Dict[str, str]]
- get_pull_request_list(state: Literal['open', 'closed', 'all'] = 'all') List[Dict[str, object]] [source]#
Retrieves all pull requests from the GitHub repository.
- Parameters:
state (Literal["open", "closed", "all"]) – The state of pull requests to retrieve. (default: :obj: all) Options are: - “open”: Retrieve only open pull requests. - “closed”: Retrieve only closed pull requests. - “all”: Retrieve all pull requests, regardless of state.
- Returns:
- A list of dictionaries where each dictionary contains the
pull request number and title.
- Return type:
list
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects representing
the functions in the toolkit.
- Return type:
List[FunctionTool]
camel.toolkits.google_maps_toolkit module#
- class camel.toolkits.google_maps_toolkit.GoogleMapsToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for interacting with GoogleMaps API. This class provides methods for validating addresses, retrieving elevation, and fetching timezone information using the Google Maps API.
- get_address_description(address: str | List[str], region_code: str | None = None, locality: str | None = None) str [source]#
Validates an address via Google Maps API, returns a descriptive summary. Validates an address using Google Maps API, returning a summary that includes information on address completion, formatted address, location coordinates, and metadata types that are true for the given address.
- Parameters:
address (Union[str, List[str]]) – The address or components to validate. Can be a single string or a list representing different parts.
region_code (str, optional) – Country code for regional restriction, helps narrow down results. (default:
None
)locality (str, optional) – Restricts validation to a specific locality, e.g., “Mountain View”. (default:
None
)
- Returns:
- Summary of the address validation results, including
information on address completion, formatted address, geographical coordinates (latitude and longitude), and metadata types true for the address.
- Return type:
str
- get_elevation(lat: float, lng: float) str [source]#
Retrieves elevation data for a given latitude and longitude. Uses the Google Maps API to fetch elevation data for the specified latitude and longitude. It handles exceptions gracefully and returns a description of the elevation, including its value in meters and the data resolution.
- Parameters:
lat (float) – The latitude of the location to query.
lng (float) – The longitude of the location to query.
- Returns:
- A description of the elevation at the specified location(s),
including the elevation in meters and the data resolution. If elevation data is not available, a message indicating this is returned.
- Return type:
str
- get_timezone(lat: float, lng: float) str [source]#
Retrieves timezone information for a given latitude and longitude. This function uses the Google Maps Timezone API to fetch timezone data for the specified latitude and longitude. It returns a natural language description of the timezone, including the timezone ID, name, standard time offset, daylight saving time offset, and the total offset from Coordinated Universal Time (UTC).
- Parameters:
lat (float) – The latitude of the location to query.
lng (float) – The longitude of the location to query.
- Returns:
- A descriptive string of the timezone information,
including the timezone ID and name, standard time offset, daylight saving time offset, and total offset from UTC.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- camel.toolkits.google_maps_toolkit.handle_googlemaps_exceptions(func: Callable[[...], Any]) Callable[[...], Any] [source]#
Decorator to catch and handle exceptions raised by Google Maps API calls.
- Parameters:
func (Callable) – The function to be wrapped by the decorator.
- Returns:
- A wrapper function that calls the wrapped function and
handles exceptions.
- Return type:
Callable
camel.toolkits.linkedin_toolkit module#
- class camel.toolkits.linkedin_toolkit.LinkedInToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for LinkedIn operations.
This class provides methods for creating a post, deleting a post, and retrieving the authenticated user’s profile information.
- create_post(text: str) dict [source]#
Creates a post on LinkedIn for the authenticated user.
- Parameters:
text (str) – The content of the post to be created.
- Returns:
- A dictionary containing the post ID and the content of
the post. If the post creation fails, the values will be None.
- Return type:
dict
- Raises:
Exception – If the post creation fails due to an error response from LinkedIn API.
- delete_post(post_id: str) str [source]#
Deletes a LinkedIn post with the specified ID for an authorized user.
This function sends a DELETE request to the LinkedIn API to delete a post with the specified ID. Before sending the request, it prompts the user to confirm the deletion.
- Parameters:
post_id (str) – The ID of the post to delete.
- Returns:
- A message indicating the result of the deletion. If the
deletion was successful, the message includes the ID of the deleted post. If the deletion was not successful, the message includes an error message.
- Return type:
str
- get_profile(include_id: bool = False) dict [source]#
Retrieves the authenticated user’s LinkedIn profile info.
This function sends a GET request to the LinkedIn API to retrieve the authenticated user’s profile information. Optionally, it also returns the user’s LinkedIn ID.
- Parameters:
include_id (bool) – Whether to include the LinkedIn profile ID in the response.
- Returns:
- A dictionary containing the user’s LinkedIn profile
information. If include_id is True, the dictionary will also include the profile ID.
- Return type:
dict
- Raises:
Exception – If the profile retrieval fails due to an error response from LinkedIn API.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
camel.toolkits.math_toolkit module#
- class camel.toolkits.math_toolkit.MathToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for mathematical operations.
This class provides methods for basic mathematical operations such as addition, subtraction, multiplication, division, and rounding.
- add(a: float, b: float) float [source]#
Adds two numbers.
- Parameters:
a (float) – The first number to be added.
b (float) – The second number to be added.
- Returns:
The sum of the two numbers.
- Return type:
float
- divide(a: float, b: float, decimal_places: int = 2) float [source]#
Divides two numbers.
- Parameters:
a (float) – The dividend in the division.
b (float) – The divisor in the division.
decimal_places (int, optional) – The number of decimal places to round to. Defaults to 2.
- Returns:
The result of dividing
a
byb
.- Return type:
float
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- multiply(a: float, b: float, decimal_places: int = 2) float [source]#
Multiplies two numbers.
- Parameters:
a (float) – The multiplier in the multiplication.
b (float) – The multiplicand in the multiplication.
decimal_places (int, optional) – The number of decimal places to round to. Defaults to 2.
- Returns:
The product of the two numbers.
- Return type:
float
- round(a: float, decimal_places: int = 0) float [source]#
Rounds a number to a specified number of decimal places.
- Parameters:
a (float) – The number to be rounded.
decimal_places (int, optional) – The number of decimal places to round to. Defaults to 0.
- Returns:
The rounded number.
- Return type:
float
camel.toolkits.open_api_toolkit module#
- class camel.toolkits.open_api_toolkit.OpenAPIToolkit[source]#
Bases:
object
A class representing a toolkit for interacting with OpenAPI APIs.
This class provides methods for interacting with APIs based on OpenAPI specifications. It dynamically generates functions for each API operation defined in the OpenAPI specification, allowing users to make HTTP requests to the API endpoints.
- apinames_filepaths_to_funs_schemas(apinames_filepaths: List[Tuple[str, str]]) Tuple[List[Callable], List[Dict[str, Any]]] [source]#
Combines functions and schemas from multiple OpenAPI specifications, using API names as keys.
This function iterates over tuples of API names and OpenAPI spec file paths, parsing each spec to generate callable functions and schema dictionaries, all organized by API name.
Args: apinames_filepaths (List[Tuple[str, str]]): A list of tuples, where
each tuple consists of: - The API name (str) as the first element. - The file path (str) to the API’s OpenAPI specification file as
the second element.
- Returns:
- Tuple[List[Callable], List[Dict[str, Any]]]:: one of callable
functions for API operations, and another of dictionaries representing the schemas from the specifications.
- generate_apinames_filepaths() List[Tuple[str, str]] [source]#
Generates a list of tuples containing API names and their corresponding file paths.
This function iterates over the OpenAPIName enum, constructs the file path for each API’s OpenAPI specification file, and appends a tuple of the API name and its file path to the list. The file paths are relative to the ‘open_api_specs’ directory located in the same directory as this script.
- Returns:
- A list of tuples where each tuple contains
two elements. The first element of each tuple is a string representing the name of an API, and the second element is a string that specifies the file path to that API’s OpenAPI specification file.
- Return type:
List[Tuple[str, str]]
- generate_openapi_funcs(api_name: str, openapi_spec: Dict[str, Any]) List[Callable] [source]#
Generates a list of Python functions based on OpenAPI specification.
This function dynamically creates a list of callable functions that represent the API operations defined in an OpenAPI specification document. Each function is designed to perform an HTTP request corresponding to an API operation (e.g., GET, POST) as defined in the specification. The functions are decorated with openapi_function_decorator, which configures them to construct and send the HTTP requests with appropriate parameters, headers, and body content.
- Parameters:
api_name (str) – The name of the API, used to prefix generated function names.
openapi_spec (Dict[str, Any]) – The OpenAPI specification as a dictionary.
- Returns:
- A list containing the generated functions. Each
function, when called, will make an HTTP request according to its corresponding API operation defined in the OpenAPI specification.
- Return type:
List[Callable]
- Raises:
ValueError – If the OpenAPI specification does not contain server information, which is necessary for determining the base URL for the API requests.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- openapi_function_decorator(api_name: str, base_url: str, path: str, method: str, openapi_security: List[Dict[str, Any]], sec_schemas: Dict[str, Dict[str, Any]], operation: Dict[str, Any]) Callable [source]#
Decorate a function to make HTTP requests based on OpenAPI specification details.
This decorator dynamically constructs and executes an API request based on the provided OpenAPI operation specifications, security requirements, and parameters. It supports operations secured with apiKey type security schemes and automatically injects the necessary API keys from environment variables. Parameters in path, query, header, and cookie are also supported.
- Parameters:
api_name (str) – The name of the API, used to retrieve API key names and URLs from the configuration.
base_url (str) – The base URL for the API.
path (str) – The path for the API endpoint, relative to the base URL.
method (str) – The HTTP method (e.g., ‘get’, ‘post’) for the request.
openapi_security (List[Dict[str, Any]]) – The global security definitions as specified in the OpenAPI specs.
sec_schemas (Dict[str, Dict[str, Any]]) – Detailed security schemes.
operation (Dict[str, Any]) – A dictionary containing the OpenAPI operation details, including parameters and request body definitions.
- Returns:
- A decorator that, when applied to a function, enables the
function to make HTTP requests based on the provided OpenAPI operation details.
- Return type:
Callable
- Raises:
TypeError – If the security requirements include unsupported types.
ValueError – If required API keys are missing from environment variables or if the content type of the request body is unsupported.
- openapi_spec_to_openai_schemas(api_name: str, openapi_spec: Dict[str, Any]) List[Dict[str, Any]] [source]#
Convert OpenAPI specification to OpenAI schema format.
This function iterates over the paths and operations defined in an OpenAPI specification, filtering out deprecated operations. For each operation, it constructs a schema in a format suitable for OpenAI, including operation metadata such as function name, description, parameters, and request bodies. It raises a ValueError if an operation lacks a description or summary.
- Parameters:
api_name (str) – The name of the API, used to prefix generated function names.
openapi_spec (Dict[str, Any]) – The OpenAPI specification as a dictionary.
- Returns:
- A list of dictionaries, each representing a
function in the OpenAI schema format, including details about the function’s name, description, and parameters.
- Return type:
List[Dict[str, Any]]
- Raises:
ValueError – If an operation in the OpenAPI specification does not have a description or summary.
Note
This function assumes that the OpenAPI specification follows the 3.0+ format.
- Reference:
- parse_openapi_file(openapi_spec_path: str) Dict[str, Any] | None [source]#
Load and parse an OpenAPI specification file.
This function utilizes the prance.ResolvingParser to parse and resolve the given OpenAPI specification file, returning the parsed OpenAPI specification as a dictionary.
- Parameters:
openapi_spec_path (str) – The file path or URL to the OpenAPI specification.
- Returns:
- The parsed OpenAPI specification
as a dictionary.
None
if the package is not installed.
- Return type:
Optional[Dict[str, Any]]
camel.toolkits.openai_function module#
- class camel.toolkits.function_tool.FunctionTool(func: Callable, openai_tool_schema: Dict[str, Any] | None = None, synthesize_schema: bool | None = False, synthesize_schema_model: BaseModelBackend | None = None, synthesize_schema_max_retries: int = 2, synthesize_output: bool | None = False, synthesize_output_model: BaseModelBackend | None = None, synthesize_output_format: Type[BaseModel] | None = None)[source]#
Bases:
object
An abstraction of a function that OpenAI chat models can call. See https://platform.openai.com/docs/api-reference/chat/create.
By default, the tool schema will be parsed from the func, or you can provide a user-defined tool schema to override.
- Parameters:
func (Callable) – The function to call. The tool schema is parsed from the function signature and docstring by default.
openai_tool_schema (Optional[Dict[str, Any]], optional) – A user-defined OpenAI tool schema to override the default result. (default:
None
)synthesize_schema (Optional[bool], optional) – Whether to enable the use of a schema assistant model to automatically synthesize the schema if validation fails or no valid schema is provided. (default:
False
)synthesize_schema_model (Optional[BaseModelBackend], optional) – An assistant model (e.g., an LLM model) used to synthesize the schema if synthesize_schema is enabled and no valid schema is provided. (default:
None
)synthesize_schema_max_retries (int, optional) – The maximum number of attempts to retry schema synthesis using the schema assistant model if the previous attempts fail. (default: 2)
synthesize_output (Optional[bool], optional) – Flag for enabling synthesis output mode, where output is synthesized based on the function’s execution. (default:
False
)synthesize_output_model (Optional[BaseModelBackend], optional) – Model used for output synthesis in synthesis mode. (default:
None
)synthesize_output_format (Optional[Type[BaseModel]], optional) – Format for the response when synthesizing output. (default:
None
)
- get_function_description() str [source]#
Gets the description of the function from the OpenAI tool schema.
- Returns:
The description of the function.
- Return type:
str
- get_function_name() str [source]#
Gets the name of the function from the OpenAI tool schema.
- Returns:
The name of the function.
- Return type:
str
- get_openai_function_schema() Dict[str, Any] [source]#
Gets the schema of the function from the OpenAI tool schema.
This method extracts and returns the function-specific part of the OpenAI tool schema associated with this function.
- Returns:
- The schema of the function within the OpenAI tool
schema.
- Return type:
Dict[str, Any]
- get_openai_tool_schema() Dict[str, Any] [source]#
Gets the OpenAI tool schema for this function.
This method returns the OpenAI tool schema associated with this function, after validating it to ensure it meets OpenAI’s specifications.
- Returns:
The OpenAI tool schema for this function.
- Return type:
Dict[str, Any]
- get_parameter(param_name: str) Dict[str, Any] [source]#
Gets the schema for a specific parameter from the function schema.
- Parameters:
param_name (str) – The name of the parameter to get the schema.
- Returns:
The schema of the specified parameter.
- Return type:
Dict[str, Any]
- get_paramter_description(param_name: str) str [source]#
Gets the description of a specific parameter from the function schema.
- Parameters:
param_name (str) – The name of the parameter to get the description.
- Returns:
The description of the specified parameter.
- Return type:
str
- property parameters: Dict[str, Any]#
Getter method for the property
parameters
.- Returns:
- the dictionary containing information of
parameters of this function.
- Return type:
Dict[str, Any]
- set_function_description(description: str) None [source]#
Sets the description of the function in the OpenAI tool schema.
- Parameters:
description (str) – The description for the function.
- set_function_name(name: str) None [source]#
Sets the name of the function in the OpenAI tool schema.
- Parameters:
name (str) – The name of the function to set.
- set_openai_function_schema(openai_function_schema: Dict[str, Any]) None [source]#
Sets the schema of the function within the OpenAI tool schema.
- Parameters:
openai_function_schema (Dict[str, Any]) – The function schema to set within the OpenAI tool schema.
- set_openai_tool_schema(schema: Dict[str, Any]) None [source]#
Sets the OpenAI tool schema for this function.
Allows setting a custom OpenAI tool schema for this function.
- Parameters:
schema (Dict[str, Any]) – The OpenAI tool schema to set.
- set_parameter(param_name: str, value: Dict[str, Any])[source]#
Sets the schema for a specific parameter in the function schema.
- Parameters:
param_name (str) – The name of the parameter to set the schema for.
value (Dict[str, Any]) – The schema to set for the parameter.
- set_paramter_description(param_name: str, description: str) None [source]#
Sets the description for a specific parameter in the function schema.
- Parameters:
param_name (str) – The name of the parameter to set the description for.
description (str) – The description for the parameter.
- synthesize_execution_output(args: tuple[Any, ...] | None = None, kwargs: Dict[str, Any] | None = None) Any [source]#
Synthesizes the output of the function based on the provided positional arguments and keyword arguments.
- Parameters:
args (Optional[tuple]) – Positional arguments to pass to the function during synthesis. (default:
None
)kwargs (Optional[Dict[str, Any]]) – Keyword arguments to pass to the function during synthesis. (default:
None
)
- Returns:
- Synthesized output from the function execution. If no
synthesis model is provided, a warning is logged.
- Return type:
Any
- synthesize_openai_tool_schema(max_retries: int | None = None) Dict[str, Any] [source]#
Synthesizes an OpenAI tool schema for the specified function.
This method uses a language model (LLM) to synthesize the OpenAI tool schema for the specified function by first generating a docstring and then creating a schema based on the function’s source code. The schema synthesis and validation process is retried up to max_retries times in case of failure.
- Parameters:
max_retries (Optional[int], optional) – The maximum number of retries for schema synthesis and validation if the process fails. (default:
None
)- Returns:
The synthesis OpenAI tool schema for the function.
- Return type:
Dict[str, Any]
- Raises:
ValueError – If schema synthesis or validation fails after the maximum number of retries, a ValueError is raised, prompting manual schema setting.
- static validate_openai_tool_schema(openai_tool_schema: Dict[str, Any]) None [source]#
Validates the OpenAI tool schema against
ToolAssistantToolsFunction
. This function checks if the providedopenai_tool_schema
adheres to the specifications required by OpenAI’sToolAssistantToolsFunction
. It ensures that the function description and parameters are correctly formatted according to JSON Schema specifications. :param openai_tool_schema: The OpenAI tool schema tovalidate.
- Raises:
ValidationError – If the schema does not comply with the specifications.
SchemaError – If the parameters do not meet JSON Schema reference specifications.
- camel.toolkits.function_tool.generate_docstring(code: str, model: BaseModelBackend | None = None) str [source]#
Generates a docstring for a given function code using LLM.
This function leverages a language model to generate a PEP 8/PEP 257-compliant docstring for a provided Python function. If no model is supplied, a default gpt-4o-mini is used.
- Parameters:
code (str) – The source code of the function.
model (Optional[BaseModelBackend]) – An optional language model backend instance. If not provided, a default gpt-4o-mini is used.
- Returns:
The generated docstring.
- Return type:
str
- camel.toolkits.function_tool.get_openai_function_schema(func: Callable) Dict[str, Any] [source]#
Generates a schema dict for an OpenAI function based on its signature.
This function is deprecated and will be replaced by
get_openai_tool_schema()
in future versions. It parses the function’s parameters and docstring to construct a JSON schema-like dictionary.- Parameters:
func (Callable) – The OpenAI function to generate the schema for.
- Returns:
- A dictionary representing the JSON schema of the
function, including its name, description, and parameter specifications.
- Return type:
Dict[str, Any]
- camel.toolkits.function_tool.get_openai_tool_schema(func: Callable) Dict[str, Any] [source]#
Generates an OpenAI JSON schema from a given Python function.
This function creates a schema compatible with OpenAI’s API specifications, based on the provided Python function. It processes the function’s parameters, types, and docstrings, and constructs a schema accordingly.
Note
Each parameter in func must have a type annotation; otherwise, it’s treated as ‘Any’.
Variable arguments (*args) and keyword arguments (**kwargs) are not supported and will be ignored.
A functional description including a brief and detailed explanation should be provided in the docstring of func.
All parameters of func must be described in its docstring.
Supported docstring styles: ReST, Google, Numpydoc, and Epydoc.
- Parameters:
func (Callable) – The Python function to be converted into an OpenAI JSON schema.
- Returns:
- A dictionary representing the OpenAI JSON schema of
the provided function.
- Return type:
Dict[str, Any]
See also
- `OpenAI API Reference
<https://platform.openai.com/docs/api-reference/assistants/object>`_
- camel.toolkits.function_tool.sanitize_and_enforce_required(parameters_dict)[source]#
Cleans and updates the function schema to conform with OpenAI’s requirements: - Removes invalid ‘default’ fields from the parameters schema. - Ensures all fields or function parameters are marked as required.
- Parameters:
parameters_dict (dict) – The dictionary representing the function schema.
- Returns:
- The updated dictionary with invalid defaults removed and all
fields set as required.
- Return type:
dict
camel.toolkits.reddit_toolkit module#
- class camel.toolkits.reddit_toolkit.RedditToolkit(retries: int = 3, delay: int = 0)[source]#
Bases:
BaseToolkit
A class representing a toolkit for Reddit operations.
This toolkit provides methods to interact with the Reddit API, allowing users to collect top posts, perform sentiment analysis on comments, and track keyword discussions across multiple subreddits.
- retries#
Number of retries for API requests in case of failure.
- Type:
int
- delay#
Delay between retries in seconds.
- Type:
int
- reddit#
An instance of the Reddit client.
- Type:
Reddit
- collect_top_posts(subreddit_name: str, post_limit: int = 5, comment_limit: int = 5) List[Dict[str, Any]] | str [source]#
Collects the top posts and their comments from a specified subreddit.
- Parameters:
subreddit_name (str) – The name of the subreddit to collect posts from.
post_limit (int) – The maximum number of top posts to collect. Defaults to 5.
comment_limit (int) – The maximum number of top comments to collect per post. Defaults to 5.
- Returns:
- A list of dictionaries, each
containing the post title and its top comments if success. String warming if credentials are not set.
- Return type:
Union[List[Dict[str, Any]], str]
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects for the
toolkit methods.
- Return type:
List[FunctionTool]
- perform_sentiment_analysis(data: List[Dict[str, Any]]) List[Dict[str, Any]] [source]#
Performs sentiment analysis on the comments collected from Reddit posts.
- Parameters:
data (List[Dict[str, Any]]) – A list of dictionaries containing Reddit post data and comments.
- Returns:
- The original data with an added ‘Sentiment
Score’ for each comment.
- Return type:
List[Dict[str, Any]]
- track_keyword_discussions(subreddits: List[str], keywords: List[str], post_limit: int = 10, comment_limit: int = 10, sentiment_analysis: bool = False) List[Dict[str, Any]] | str [source]#
Tracks discussions about specific keywords in specified subreddits.
- Parameters:
subreddits (List[str]) – A list of subreddit names to search within.
keywords (List[str]) – A list of keywords to track in the subreddit discussions.
post_limit (int) – The maximum number of top posts to collect per subreddit. Defaults to 10.
comment_limit (int) – The maximum number of top comments to collect per post. Defaults to 10.
sentiment_analysis (bool) – If True, performs sentiment analysis on the comments. Defaults to False.
- Returns:
- A list of dictionaries
containing the subreddit name, post title, comment body, and upvotes for each comment that contains the specified keywords if success. String warming if credentials are not set.
- Return type:
Union[List[Dict[str, Any]], str]
camel.toolkits.retrieval_toolkit module#
- class camel.toolkits.retrieval_toolkit.RetrievalToolkit(auto_retriever: AutoRetriever | None = None)[source]#
Bases:
BaseToolkit
A class representing a toolkit for information retrieval.
This class provides methods for retrieving information from a local vector storage system based on a specified query.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- information_retrieval(query: str, contents: str | List[str], top_k: int = 1, similarity_threshold: float = 0.7) str [source]#
Retrieves information from a local vector storage based on the specified query. This function connects to a local vector storage system and retrieves relevant information by processing the input query. It is essential to use this function when the answer to a question requires external knowledge sources.
- Parameters:
query (str) – The question or query for which an answer is required.
contents (Union[str, List[str]]) – Local file paths, remote URLs or string contents.
top_k (int, optional) – The number of top results to return during retrieve. Must be a positive integer. Defaults to DEFAULT_TOP_K_RESULTS.
similarity_threshold (float, optional) – The similarity threshold for filtering results. Defaults to DEFAULT_SIMILARITY_THRESHOLD.
- Returns:
- The information retrieved in response to the query, aggregated
and formatted as a string.
- Return type:
str
Example
# Retrieve information about CAMEL AI. information_retrieval(query = “How to contribute to CAMEL AI?”,
contents=”camel-ai/camel”)
camel.toolkits.search_toolkit module#
- class camel.toolkits.search_toolkit.SearchToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for web search.
This class provides methods for searching information on the web using search engines like Google, DuckDuckGo, Wikipedia and Wolfram Alpha, Brave.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- query_wolfram_alpha(query: str, is_detailed: bool = False) str | Dict[str, Any] [source]#
Queries Wolfram|Alpha and returns the result. Wolfram|Alpha is an answer engine developed by Wolfram Research. It is offered as an online service that answers factual queries by computing answers from externally sourced data.
- Parameters:
query (str) – The query to send to Wolfram Alpha.
is_detailed (bool) – Whether to include additional details including step by step information in the result. (default:
False
)
- Returns:
- The result from Wolfram Alpha.
Returns a string if is_detailed is False, otherwise returns a dictionary with detailed information.
- Return type:
Union[str, Dict[str, Any]]
- search_brave(q: str, country: str = 'US', search_lang: str = 'en', ui_lang: str = 'en-US', count: int = 20, offset: int = 0, safesearch: str = 'moderate', freshness: str | None = None, text_decorations: bool = True, spellcheck: bool = True, result_filter: str | None = None, goggles_id: str | None = None, units: str | None = None, extra_snippets: bool | None = None, summary: bool | None = None) Dict[str, Any] [source]#
This function queries the Brave search engine API and returns a dictionary, representing a search result. See https://api.search.brave.com/app/documentation/web-search/query for more details.
- Parameters:
q (str) – The user’s search query term. Query cannot be empty. Maximum of 400 characters and 50 words in the query.
country (str) – The search query country where results come from. The country string is limited to 2 character country codes of supported countries. For a list of supported values, see Country Codes. (default: :obj:`US `)
search_lang (str) – The search language preference. The 2 or more character language code for which search results are provided. For a list of possible values, see Language Codes.
ui_lang (str) – User interface language preferred in response. Usually of the format ‘<language_code>-<country_code>’. For more, see RFC 9110. For a list of supported values, see UI Language Codes.
count (int) – The number of search results returned in response. The maximum is 20. The actual number delivered may be less than requested. Combine this parameter with offset to paginate search results.
offset (int) – The zero based offset that indicates number of search results per page (count) to skip before returning the result. The maximum is 9. The actual number delivered may be less than requested based on the query. In order to paginate results use this parameter together with count. For example, if your user interface displays 20 search results per page, set count to 20 and offset to 0 to show the first page of results. To get subsequent pages, increment offset by 1 (e.g. 0, 1, 2). The results may overlap across multiple pages.
safesearch (str) –
Filters search results for adult content. The following values are supported: - ‘off’: No filtering is done. - ‘moderate’: Filters explicit content, like images and videos,
but allows adult domains in the search results.
’strict’: Drops all adult content from search results.
freshness (Optional[str]) –
Filters search results by when they were discovered: - ‘pd’: Discovered within the last 24 hours. - ‘pw’: Discovered within the last 7 Days. - ‘pm’: Discovered within the last 31 Days. - ‘py’: Discovered within the last 365 Days. - ‘YYYY-MM-DDtoYYYY-MM-DD’: Timeframe is also supported by
specifying the date range e.g. ‘2022-04-01to2022-07-30’.
text_decorations (bool) – Whether display strings (e.g. result snippets) should include decoration markers (e.g. highlighting characters).
spellcheck (bool) – Whether to spellcheck provided query. If the spellchecker is enabled, the modified query is always used for search. The modified query can be found in altered key from the query response model.
result_filter (Optional[str]) – A comma delimited string of result types to include in the search response. Not specifying this parameter will return back all result types in search response where data is available and a plan with the corresponding option is subscribed. The response always includes query and type to identify any query modifications and response type respectively. Available result filter values are: - ‘discussions’ - ‘faq’ - ‘infobox’ - ‘news’ - ‘query’ - ‘summarizer’ - ‘videos’ - ‘web’ - ‘locations’
goggles_id (Optional[str]) – Goggles act as a custom re-ranking on top of Brave’s search index. For more details, refer to the Goggles repository.
units (Optional[str]) – The measurement units. If not provided, units are derived from search country. Possible values are: - ‘metric’: The standardized measurement system - ‘imperial’: The British Imperial system of units.
extra_snippets (Optional[bool]) – A snippet is an excerpt from a page you get as a result of the query, and extra_snippets allow you to get up to 5 additional, alternative excerpts. Only available under Free AI, Base AI, Pro AI, Base Data, Pro Data and Custom plans.
summary (Optional[bool]) – This parameter enables summary key generation in web search results. This is required for summarizer to be enabled.
- Returns:
A dictionary representing a search result.
- Return type:
Dict[str, Any]
- search_duckduckgo(query: str, source: str = 'text', max_results: int = 5) List[Dict[str, Any]] [source]#
Use DuckDuckGo search engine to search information for the given query.
This function queries the DuckDuckGo API for related topics to the given search term. The results are formatted into a list of dictionaries, each representing a search result.
- Parameters:
query (str) – The query to be searched.
source (str) – The type of information to query (e.g., “text”, “images”, “videos”). Defaults to “text”.
max_results (int) – Max number of results, defaults to 5.
- Returns:
- A list of dictionaries where each dictionary
represents a search result.
- Return type:
List[Dict[str, Any]]
- search_google(query: str, num_result_pages: int = 5) List[Dict[str, Any]] [source]#
Use Google search engine to search information for the given query.
- Parameters:
query (str) – The query to be searched.
num_result_pages (int) – The number of result pages to retrieve.
- Returns:
A list of dictionaries where each dictionary represents a website.
Each dictionary contains the following keys: - ‘result_id’: A number in order. - ‘title’: The title of the website. - ‘description’: A brief description of the website. - ‘long_description’: More detail of the website. - ‘url’: The URL of the website.
Example: {
’result_id’: 1, ‘title’: ‘OpenAI’, ‘description’: ‘An organization focused on ensuring that artificial general intelligence benefits all of humanity.’, ‘long_description’: ‘OpenAI is a non-profit artificial intelligence research company. Our goal is to advance digital intelligence in the way that is most likely to benefit humanity as a whole’, ‘url’: ‘https://www.openai.com’
}
title, description, url of a website.
- Return type:
List[Dict[str, Any]]
- search_linkup(query: str, depth: Literal['standard', 'deep'] = 'standard', output_type: Literal['searchResults', 'sourcedAnswer', 'structured'] = 'searchResults', structured_output_schema: Type[BaseModel] | str | None = None) Dict[str, Any] [source]#
Search for a query in the Linkup API and return results in various formats.
- Parameters:
query (str) – The search query.
depth (Literal["standard", "deep"]) – The depth of the search. “standard” for a straightforward search, “deep” for a more comprehensive search.
(Literal["searchResults" (output_type) – “structured”]): The type of output: - “searchResults” for raw search results, - “sourcedAnswer” for an answer with supporting sources, - “structured” for output based on a provided schema.
"sourcedAnswer" – “structured”]): The type of output: - “searchResults” for raw search results, - “sourcedAnswer” for an answer with supporting sources, - “structured” for output based on a provided schema.
- :param“structured”]): The type of output:
“searchResults” for raw search results,
“sourcedAnswer” for an answer with supporting sources,
“structured” for output based on a provided schema.
- Parameters:
structured_output_schema (Union[Type[BaseModel], str, None]) – If output_type is “structured”,specify the schema of the output. Can be a Pydantic BaseModel or a JSON schema string.
- Returns:
- A dictionary representing the search result. The
structure depends on the output_type. If an error occurs, returns an error message.
- Return type:
Dict[str, Any]
- search_wiki(entity: str) str [source]#
- Search the entity in WikiPedia and return the summary of the
required page, containing factual information about the given entity.
- Parameters:
entity (str) – The entity to be searched.
- Returns:
- The search result. If the page corresponding to the entity
exists, return the summary of this entity in a string.
- Return type:
str
- tavily_search(query: str, num_results: int = 5, **kwargs) List[Dict[str, Any]] [source]#
Use Tavily Search API to search information for the given query.
- Parameters:
query (str) – The query to be searched.
num_results (int) – The number of search results to retrieve (default is 5).
**kwargs –
Additional optional parameters supported by Tavily’s API: - search_depth (str): “basic” or “advanced” search depth. - topic (str): The search category, e.g., “general” or “news.” - days (int): Time frame in days for news-related searches. - max_results (int): Max number of results to return
(overrides num_results).
See https://docs.tavily.com/docs/python-sdk/tavily-search/ api-reference for details.
- Returns:
- A list of dictionaries representing search
results. Each dictionary contains: - ‘result_id’ (int): The result’s index. - ‘title’ (str): The title of the result. - ‘description’ (str): A brief description of the result. - ‘long_description’ (str): Detailed information, if available. - ‘url’ (str): The URL of the result. - ‘content’ (str): Relevant content from the search result. - ‘images’ (list): A list of related images (if
include_images is True).
’published_date’ (str): Publication date for news topics (if available).
- Return type:
List[Dict[str, Any]]
camel.toolkits.slack_toolkit module#
- class camel.toolkits.slack_toolkit.SlackToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for Slack operations.
This class provides methods for Slack operations such as creating a new channel, joining an existing channel, leaving a channel.
- create_slack_channel(name: str, is_private: bool | None = True) str [source]#
Creates a new slack channel, either public or private.
- Parameters:
name (str) – Name of the public or private channel to create.
is_private (bool, optional) – Whether to create a private channel instead of a public one. Defaults to True.
- Returns:
- JSON string containing information about Slack
channel created.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel information.
- delete_slack_message(time_stamp: str, channel_id: str) str [source]#
Delete a message to a Slack channel.
- Parameters:
time_stamp (str) – Timestamp of the message to be deleted.
channel_id (str) – The ID of the Slack channel to delete message.
- Returns:
- A confirmation message indicating whether the message
was delete successfully or an error message.
- Return type:
str
- Raises:
SlackApiError – If an error occurs while sending the message.
- get_slack_channel_information() str [source]#
- Retrieve Slack channels and return relevant information in JSON
format.
- Returns:
JSON string containing information about Slack channels.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel information.
- get_slack_channel_message(channel_id: str) str [source]#
Retrieve messages from a Slack channel.
- Parameters:
channel_id (str) – The ID of the Slack channel to retrieve messages from.
- Returns:
JSON string containing filtered message data.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel message.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- join_slack_channel(channel_id: str) str [source]#
Joins an existing Slack channel.
- Parameters:
channel_id (str) – The ID of the Slack channel to join.
- Returns:
- A confirmation message indicating whether join successfully
or an error message.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel information.
- leave_slack_channel(channel_id: str) str [source]#
Leaves an existing Slack channel.
- Parameters:
channel_id (str) – The ID of the Slack channel to leave.
- Returns:
- A confirmation message indicating whether leave successfully
or an error message.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel information.
- send_slack_message(message: str, channel_id: str, user: str | None = None) str [source]#
Send a message to a Slack channel.
- Parameters:
message (str) – The message to send.
channel_id (str) – The ID of the Slack channel to send message.
user (Optional[str]) – The user ID of the recipient. Defaults to None.
- Returns:
- A confirmation message indicating whether the message was sent
successfully or an error message.
- Return type:
str
- Raises:
SlackApiError – If an error occurs while sending the message.
camel.toolkits.twitter_toolkit module#
- class camel.toolkits.twitter_toolkit.TwitterToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for Twitter operations.
This class provides methods for creating a tweet, deleting a tweet, and getting the authenticated user’s profile information.
References
https://developer.x.com/en/portal/dashboard
Notes
To use this toolkit, you need to set the following environment variables: - TWITTER_CONSUMER_KEY: The consumer key for the Twitter API. - TWITTER_CONSUMER_SECRET: The consumer secret for the Twitter API. - TWITTER_ACCESS_TOKEN: The access token for the Twitter API. - TWITTER_ACCESS_TOKEN_SECRET: The access token secret for the Twitter
API.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- camel.toolkits.twitter_toolkit.create_tweet(text: str, poll_options: List[str] | None = None, poll_duration_minutes: int | None = None, quote_tweet_id: int | str | None = None) str [source]#
Creates a new tweet, optionally including a poll or a quote tweet, or simply a text-only tweet.
This function sends a POST request to the Twitter API to create a new tweet. The tweet can be a text-only tweet, or optionally include a poll or be a quote tweet. A confirmation prompt is presented to the user before the tweet is created.
- Parameters:
text (str) – The text of the tweet. The Twitter character limit for a single tweet is 280 characters.
poll_options (Optional[List[str]]) – A list of poll options for a tweet with a poll.
poll_duration_minutes (Optional[int]) – Duration of the poll in minutes for a tweet with a poll. This is only required if the request includes poll_options.
quote_tweet_id (Optional[Union[int, str]]) – Link to the tweet being quoted.
- Returns:
- A message indicating the success of the tweet creation,
including the tweet ID and text. If the request to the Twitter API is not successful, the return is an error message.
- Return type:
str
Note
You can only provide either the quote_tweet_id parameter or the pair of poll_duration_minutes and poll_options parameters, not both.
- camel.toolkits.twitter_toolkit.delete_tweet(tweet_id: str) str [source]#
Deletes a tweet with the specified ID for an authorized user.
This function sends a DELETE request to the Twitter API to delete a tweet with the specified ID. Before sending the request, it prompts the user to confirm the deletion.
- Parameters:
tweet_id (str) – The ID of the tweet to delete.
- Returns:
- A message indicating the result of the deletion. If the
deletion was successful, the message includes the ID of the deleted tweet. If the deletion was not successful, the message includes an error message.
- Return type:
str
- camel.toolkits.twitter_toolkit.get_my_user_profile() str [source]#
Retrieves the authenticated user’s Twitter profile info.
This function sends a GET request to the Twitter API to retrieve the authenticated user’s profile information, including their pinned tweet. It then formats this information into a readable report.
- Returns:
- A formatted report of the authenticated user’s Twitter profile
information. This includes their ID, name, username, description, location, most recent tweet ID, profile image URL, account creation date, protection status, verification type, public metrics, and pinned tweet information. If the request to the Twitter API is not successful, the return is an error message.
- Return type:
str
- camel.toolkits.twitter_toolkit.get_user_by_username(username: str) str [source]#
Retrieves one user’s Twitter profile info by username (handle).
This function sends a GET request to the Twitter API to retrieve the user’s profile information, including their pinned tweet. It then formats this information into a readable report.
- Parameters:
username (str) – The username (handle) of the user to retrieve.
- Returns:
- A formatted report of the user’s Twitter profile information.
This includes their ID, name, username, description, location, most recent tweet ID, profile image URL, account creation date, protection status, verification type, public metrics, and pinned tweet information. If the request to the Twitter API is not successful, the return is an error message.
- Return type:
str
camel.toolkits.weather_toolkit module#
- class camel.toolkits.weather_toolkit.WeatherToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for interacting with weather data.
This class provides methods for fetching weather data for a given city using the OpenWeatherMap API.
- get_openweathermap_api_key() str [source]#
Retrieve the OpenWeatherMap API key from environment variables.
- Returns:
The OpenWeatherMap API key.
- Return type:
str
- Raises:
ValueError – If the API key is not found in the environment
variables. –
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- get_weather_data(city: str, temp_units: Literal['kelvin', 'celsius', 'fahrenheit'] = 'kelvin', wind_units: Literal['meters_sec', 'miles_hour', 'knots', 'beaufort'] = 'meters_sec', visibility_units: Literal['meters', 'miles'] = 'meters', time_units: Literal['unix', 'iso', 'date'] = 'unix') str [source]#
Fetch and return a comprehensive weather report for a given city as a string. The report includes current weather conditions, temperature, wind details, visibility, and sunrise/sunset times, all formatted as a readable string.
The function interacts with the OpenWeatherMap API to retrieve the data.
- Parameters:
city (str) – The name of the city for which the weather information is desired. Format “City, CountryCode” (e.g., “Paris, FR” for Paris, France). If the country code is not provided, the API will search for the city in all countries, which may yield incorrect results if multiple cities with the same name exist.
temp_units (Literal['kelvin', 'celsius', 'fahrenheit']) – Units for temperature. (default:
kelvin
)wind_units – (Literal[‘meters_sec’, ‘miles_hour’, ‘knots’, ‘beaufort’]): Units for wind speed. (default:
meters_sec
)visibility_units (Literal['meters', 'miles']) – Units for visibility distance. (default:
meters
)time_units (Literal['unix', 'iso', 'date']) – Format for sunrise and sunset times. (default:
unix
)
- Returns:
- A string containing the fetched weather data, formatted in a
readable manner. If an error occurs, a message indicating the error will be returned instead.
- Return type:
str
- Example of return string:
“Weather in Paris, FR: 15°C, feels like 13°C. Max temp: 17°C, Min temp : 12°C. Wind: 5 m/s at 270 degrees. Visibility: 10 kilometers. Sunrise at 05:46:05 (UTC), Sunset at 18:42:20 (UTC).”
Note
- Please ensure that the API key is valid and has permissions
to access the weather data.
Module contents#
- class camel.toolkits.ArxivToolkit[source]#
Bases:
BaseToolkit
A toolkit for interacting with the arXiv API to search and download academic papers.
- download_papers(query: str, paper_ids: List[str] | None = None, max_results: int | None = 5, output_dir: str | None = './') str [source]#
Downloads PDFs of academic papers from arXiv based on the provided query.
- Parameters:
query (str) – The search query string.
paper_ids (List[str], optional) – A list of specific arXiv paper IDs to download. (default: :obj: None)
max_results (int, optional) – The maximum number of search results to download. (default: :obj: 5)
output_dir (str, optional) – The directory to save the downloaded PDFs. Defaults to the current directory.
- Returns:
Status message indicating success or failure.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- search_papers(query: str, paper_ids: List[str] | None = None, max_results: int | None = 5) List[Dict[str, str]] [source]#
Searches for academic papers on arXiv using a query string and optional paper IDs.
- Parameters:
query (str) – The search query string.
paper_ids (List[str], optional) – A list of specific arXiv paper IDs to search for. (default: :obj: None)
max_results (int, optional) – The maximum number of search results to return. (default: :obj: 5)
- Returns:
- A list of dictionaries, each containing
information about a paper, including title, published date, authors, entry ID, summary, and extracted text from the paper.
- Return type:
List[Dict[str, str]]
- class camel.toolkits.AskNewsToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for interacting with the AskNews API.
This class provides methods for fetching news, stories, and other content based on user queries using the AskNews API.
- get_news(query: str, n_articles: int = 10, return_type: Literal['string', 'dicts', 'both'] = 'string', method: Literal['nl', 'kw'] = 'kw') str | dict | Tuple[str, dict] [source]#
Fetch news or stories based on a user query.
- Parameters:
query (str) – The search query for fetching relevant news.
n_articles (int) – Number of articles to include in the response. (default:
10
)return_type (Literal["string", "dicts", "both"]) – The format of the return value. (default:
"string"
)method (Literal["nl", "kw"]) – The search method, either “nl” for natural language or “kw” for keyword search. (default:
"kw"
)
- Returns:
- A string, dictionary,
or both containing the news or story content, or error message if the process fails.
- Return type:
Union[str, dict, Tuple[str, dict]]
- get_stories(query: str, categories: List[Literal['Politics', 'Economy', 'Finance', 'Science', 'Technology', 'Sports', 'Climate', 'Environment', 'Culture', 'Entertainment', 'Business', 'Health', 'International']], reddit: int = 3, expand_updates: bool = True, max_updates: int = 2, max_articles: int = 10) dict | str [source]#
Fetch stories based on the provided parameters.
- Parameters:
query (str) – The search query for fetching relevant stories.
categories (list) – The categories to filter stories by.
reddit (int) – Number of Reddit threads to include. (default:
3
)expand_updates (bool) – Whether to include detailed updates. (default:
True
)max_updates (int) – Maximum number of recent updates per story. (default:
2
)max_articles (int) – Maximum number of articles associated with each update. (default:
10
)
- Returns:
- A dictionary containing the stories and their
associated data, or error message if the process fails.
- Return type:
Unio[dict, str]
- get_tools() List[FunctionTool] [source]#
- Returns a list of FunctionTool objects representing the functions
in the toolkit.
- Returns:
- A list of FunctionTool objects representing
the functions in the toolkit.
- Return type:
List[FunctionTool]
- get_web_search(queries: List[str], return_type: Literal['string', 'dicts', 'both'] = 'string') str | dict | Tuple[str, dict] [source]#
Perform a live web search based on the given queries.
- Parameters:
queries (List[str]) – A list of search queries.
return_type (Literal["string", "dicts", "both"]) – The format of the return value. (default:
"string"
)
- Returns:
- A string,
dictionary, or both containing the search results, or error message if the process fails.
- Return type:
Union[str, dict, Tuple[str, dict]]
- query_finance(asset: Literal['bitcoin', 'ethereum', 'cardano', 'uniswap', 'ripple', 'solana', 'polkadot', 'polygon', 'chainlink', 'tether', 'dogecoin', 'monero', 'tron', 'binance', 'aave', 'tesla', 'microsoft', 'amazon'], metric: Literal['news_positive', 'news_negative', 'news_total', 'news_positive_weighted', 'news_negative_weighted', 'news_total_weighted'] = 'news_positive', return_type: Literal['list', 'string'] = 'string', date_from: datetime | None = None, date_to: datetime | None = None) list | str [source]#
Fetch asset sentiment data for a given asset, metric, and date range.
- Parameters:
asset (Literal) – The asset for which to fetch sentiment data.
metric (Literal) – The sentiment metric to analyze.
return_type (Literal["list", "string"]) – The format of the return value. (default:
"string"
)date_from (datetime, optional) – The start date and time for the data in ISO 8601 format.
date_to (datetime, optional) – The end date and time for the data in ISO 8601 format.
- Returns:
- A list of dictionaries containing the datetime
and value or a string describing all datetime and value pairs for providing quantified time-series data for news sentiment on topics of interest, or an error message if the process fails.
- Return type:
Union[list, str]
- search_reddit(keywords: List[str], n_threads: int = 5, return_type: Literal['string', 'dicts', 'both'] = 'string', method: Literal['nl', 'kw'] = 'kw') str | dict | Tuple[str, dict] [source]#
Search Reddit based on the provided keywords.
- Parameters:
keywords (List[str]) – The keywords to search for on Reddit.
n_threads (int) – Number of Reddit threads to summarize and return. (default:
5
)return_type (Literal["string", "dicts", "both"]) – The format of the return value. (default:
"string"
)method (Literal["nl", "kw"]) – The search method, either “nl” for natural language or “kw” for keyword search. (default:
"kw"
)
- Returns:
- The Reddit search
results as a string, dictionary, or both, or error message if the process fails.
- Return type:
Union[str, dict, Tuple[str, dict]]
- class camel.toolkits.AsyncAskNewsToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for interacting with the AskNews API asynchronously.
This class provides methods for fetching news, stories, and other content based on user queries using the AskNews API.
- async get_news(query: str, n_articles: int = 10, return_type: Literal['string', 'dicts', 'both'] = 'string', method: Literal['nl', 'kw'] = 'kw') str | dict | Tuple[str, dict] [source]#
Fetch news or stories based on a user query.
- Parameters:
query (str) – The search query for fetching relevant news or stories.
n_articles (int) – Number of articles to include in the response. (default: :obj:10)
return_type (Literal["string", "dicts", "both"]) – The format of the return value. (default: :obj:”string”)
method (Literal["nl", "kw"]) – The search method, either “nl” for natural language or “kw” for keyword search. (default: :obj:”kw”)
- Returns:
- A string,
dictionary, or both containing the news or story content, or error message if the process fails.
- Return type:
Union[str, dict, Tuple[str, dict]]
- async get_stories(query: str, categories: List[Literal['Politics', 'Economy', 'Finance', 'Science', 'Technology', 'Sports', 'Climate', 'Environment', 'Culture', 'Entertainment', 'Business', 'Health', 'International']], reddit: int = 3, expand_updates: bool = True, max_updates: int = 2, max_articles: int = 10) dict | str [source]#
Fetch stories based on the provided parameters.
- Parameters:
query (str) – The search query for fetching relevant stories.
categories (list) – The categories to filter stories by.
reddit (int) – Number of Reddit threads to include. (default:
3
)expand_updates (bool) – Whether to include detailed updates. (default:
True
)max_updates (int) – Maximum number of recent updates per story. (default:
2
)max_articles (int) – Maximum number of articles associated with each update. (default:
10
)
- Returns:
- A dictionary containing the stories and their
associated data, or error message if the process fails.
- Return type:
Unio[dict, str]
- get_tools() List[FunctionTool] [source]#
- Returns a list of FunctionTool objects representing the functions
in the toolkit.
- Returns:
- A list of FunctionTool objects representing
the functions in the toolkit.
- Return type:
List[FunctionTool]
- async get_web_search(queries: List[str], return_type: Literal['string', 'dicts', 'both'] = 'string') str | dict | Tuple[str, dict] [source]#
Perform a live web search based on the given queries.
- Parameters:
queries (List[str]) – A list of search queries.
return_type (Literal["string", "dicts", "both"]) – The format of the return value. (default:
"string"
)
- Returns:
- A string,
dictionary, or both containing the search results, or error message if the process fails.
- Return type:
Union[str, dict, Tuple[str, dict]]
- async query_finance(asset: Literal['bitcoin', 'ethereum', 'cardano', 'uniswap', 'ripple', 'solana', 'polkadot', 'polygon', 'chainlink', 'tether', 'dogecoin', 'monero', 'tron', 'binance', 'aave', 'tesla', 'microsoft', 'amazon'], metric: Literal['news_positive', 'news_negative', 'news_total', 'news_positive_weighted', 'news_negative_weighted', 'news_total_weighted'] = 'news_positive', return_type: Literal['list', 'string'] = 'string', date_from: datetime | None = None, date_to: datetime | None = None) list | str [source]#
Fetch asset sentiment data for a given asset, metric, and date range.
- Parameters:
asset (Literal) – The asset for which to fetch sentiment data.
metric (Literal) – The sentiment metric to analyze.
return_type (Literal["list", "string"]) – The format of the return value. (default:
"string"
)date_from (datetime, optional) – The start date and time for the data in ISO 8601 format.
date_to (datetime, optional) – The end date and time for the data in ISO 8601 format.
- Returns:
- A list of dictionaries containing the datetime
and value or a string describing all datetime and value pairs for providing quantified time-series data for news sentiment on topics of interest, or an error message if the process fails.
- Return type:
Union[list, str]
- async search_reddit(keywords: List[str], n_threads: int = 5, return_type: Literal['string', 'dicts', 'both'] = 'string', method: Literal['nl', 'kw'] = 'kw') str | dict | Tuple[str, dict] [source]#
Search Reddit based on the provided keywords.
- Parameters:
keywords (list) – The keywords to search for on Reddit.
n_threads (int) – Number of Reddit threads to summarize and return. (default: :obj:5)
return_type (Literal["string", "dicts", "both"]) – The format of the return value. (default: :obj:”string”)
method (Literal["nl", "kw"]) – The search method, either “nl” for natural language or “kw” for keyword search. (default: :obj:”kw”)
- Returns:
- The Reddit search
results as a string, dictionary, or both, or error message if the process fails.
- Return type:
Union[str, dict, Tuple[str, dict]]
- class camel.toolkits.BaseToolkit[source]#
Bases:
object
Base class for toolkits.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- class camel.toolkits.CodeExecutionToolkit(sandbox: Literal['internal_python', 'jupyter', 'docker', 'subprocess', 'e2b'] = 'internal_python', verbose: bool = False, unsafe_mode: bool = False, import_white_list: List[str] | None = None, require_confirm: bool = False)[source]#
Bases:
BaseToolkit
A tookit for code execution.
- Parameters:
sandbox (str) – The environment type used to execute code.
verbose (bool) – Whether to print the output of the code execution. (default:
False
)unsafe_mode (bool) – If True, the interpreter runs the code by eval() without any security check. (default:
False
)import_white_list (Optional[List[str]]) – A list of allowed imports. (default:
None
)require_confirm (bool) – Whether to require confirmation before executing code. (default:
False
)
- execute_code(code: str) str [source]#
Execute a given code snippet.
- Parameters:
code (str) – The input code to the Code Interpreter tool call.
- Returns:
The text output from the Code Interpreter tool call.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- class camel.toolkits.DalleToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for image generation using OpenAI’s DALL-E model.
- base64_to_image(base64_string: str) Image | None [source]#
Converts a base64 encoded string into a PIL Image object.
- Parameters:
base64_string (str) – The base64 encoded string of the image.
- Returns:
- The PIL Image object or None if conversion
fails.
- Return type:
Optional[Image.Image]
- get_dalle_img(prompt: str, image_dir: str = 'img') str [source]#
- Generate an image using OpenAI’s DALL-E model.
The generated image is saved to the specified directory.
- Parameters:
prompt (str) – The text prompt based on which the image is generated.
image_dir (str) – The directory to save the generated image. Defaults to ‘img’.
- Returns:
The path to the saved image.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- image_path_to_base64(image_path: str) str [source]#
Converts the file path of an image to a Base64 encoded string.
- Parameters:
image_path (str) – The path to the image file.
- Returns:
- A Base64 encoded string representing the content of the image
file.
- Return type:
str
- image_to_base64(image: Image) str [source]#
Converts an image into a base64-encoded string.
This function takes an image object as input, encodes the image into a PNG format base64 string, and returns it. If the encoding process encounters an error, it prints the error message and returns None.
- Parameters:
image – The image object to be encoded, supports any image format that can be saved in PNG format.
- Returns:
A base64-encoded string of the image.
- Return type:
str
- class camel.toolkits.DappierToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for interacting with the Dappier API.
This class provides methods for searching real time data and fetching ai recommendations across key verticals like News, Finance, Stock Market, Sports, Weather and more.
- get_ai_recommendations(query: str, data_model_id: str = 'dm_01j0pb465keqmatq9k83dthx34', similarity_top_k: int = 9, ref: str | None = None, num_articles_ref: int = 0, search_algorithm: Literal['most_recent', 'semantic', 'most_recent_semantic', 'trending'] = 'most_recent') List[Dict[str, str]] | Dict[str, str] [source]#
Retrieve AI-powered recommendations based on the provided query and data model.
This function fetches real-time AI-generated recommendations using the specified data model and search algorithm. The results include personalized content based on the query and, optionally, relevance to a specific reference domain.
- Supported Data Models:
dm_01j0pb465keqmatq9k83dthx34:
Real-time news, updates, and personalized content from top sports sources such as Sportsnaut, Forever Blueshirts, Minnesota Sports Fan, LAFB Network, Bounding Into Sports, and Ringside Intel. - dm_01j0q82s4bfjmsqkhs3ywm3x6y: Real-time updates, analysis, and personalized content from top sources like The Mix, Snipdaily, Nerdable, and Familyproof.
- Parameters:
query (str) – The user query for retrieving recommendations.
data_model_id (str, optional) – The data model ID to use for recommendations. Data model IDs always start with the prefix “dm_”. (default: :obj: dm_01j0pb465keqmatq9k83dthx34)
similarity_top_k (int, optional) – The number of top documents to retrieve based on similarity. (default: :obj: 9)
ref (Optional[str], optional) – The site domain where AI recommendations should be displayed. (default: :obj: None)
num_articles_ref (int, optional) – The minimum number of articles to return from the specified reference domain (ref). The remaining articles will come from other sites in the RAG model. (default: :obj: 0)
(Literal[ (search_algorithm) – “most_recent”, “semantic”, “most_recent_semantic”, “trending”, ], optional): The search algorithm to use for retrieving articles. (default: :obj: most_recent)
- Returns:
- A list of recommended articles or content
based on the specified parameters, query, and data model.
- Return type:
List[Dict[str, str]]
Note
Multiple data model IDs are available and can be found at: https://marketplace.dappier.com/marketplace
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects representing
the functions in the toolkit.
- Return type:
List[FunctionTool]
- search_real_time_data(query: str, ai_model_id: str = 'am_01j06ytn18ejftedz6dyhz2b15') str [source]#
Search real-time data using an AI model.
This function accesses real-time information using the specified AI model based on the given query. Depending on the AI model ID, the data retrieved can vary between general web search results or financial news and stock prices.
- Supported AI Models:
am_01j06ytn18ejftedz6dyhz2b15:
Access real-time Google web search results, including the latest news, weather updates, travel details, deals, and more. - am_01j749h8pbf7ns8r1bq9s2evrh: Access real-time financial news, stock prices, and trades from polygon.io, with AI-powered insights and up-to-the-minute updates.
- Parameters:
query (str) – The user-provided query. Examples include: - “How is the weather today in Austin, TX?” - “What is the latest news for Meta?” - “What is the stock price for AAPL?”
ai_model_id (str, optional) – The AI model ID to use for the query. The AI model ID always starts with the prefix “am_”. (default: am_01j06ytn18ejftedz6dyhz2b15)
- Returns:
- The search result corresponding to the provided query and
AI model ID. This may include real time search data, depending on the selected AI model.
- Return type:
str
Note
Multiple AI model IDs are available, which can be found at: https://marketplace.dappier.com/marketplace
- class camel.toolkits.FunctionTool(func: Callable, openai_tool_schema: Dict[str, Any] | None = None, synthesize_schema: bool | None = False, synthesize_schema_model: BaseModelBackend | None = None, synthesize_schema_max_retries: int = 2, synthesize_output: bool | None = False, synthesize_output_model: BaseModelBackend | None = None, synthesize_output_format: Type[BaseModel] | None = None)[source]#
Bases:
object
An abstraction of a function that OpenAI chat models can call. See https://platform.openai.com/docs/api-reference/chat/create.
By default, the tool schema will be parsed from the func, or you can provide a user-defined tool schema to override.
- Parameters:
func (Callable) – The function to call. The tool schema is parsed from the function signature and docstring by default.
openai_tool_schema (Optional[Dict[str, Any]], optional) – A user-defined OpenAI tool schema to override the default result. (default:
None
)synthesize_schema (Optional[bool], optional) – Whether to enable the use of a schema assistant model to automatically synthesize the schema if validation fails or no valid schema is provided. (default:
False
)synthesize_schema_model (Optional[BaseModelBackend], optional) – An assistant model (e.g., an LLM model) used to synthesize the schema if synthesize_schema is enabled and no valid schema is provided. (default:
None
)synthesize_schema_max_retries (int, optional) – The maximum number of attempts to retry schema synthesis using the schema assistant model if the previous attempts fail. (default: 2)
synthesize_output (Optional[bool], optional) – Flag for enabling synthesis output mode, where output is synthesized based on the function’s execution. (default:
False
)synthesize_output_model (Optional[BaseModelBackend], optional) – Model used for output synthesis in synthesis mode. (default:
None
)synthesize_output_format (Optional[Type[BaseModel]], optional) – Format for the response when synthesizing output. (default:
None
)
- get_function_description() str [source]#
Gets the description of the function from the OpenAI tool schema.
- Returns:
The description of the function.
- Return type:
str
- get_function_name() str [source]#
Gets the name of the function from the OpenAI tool schema.
- Returns:
The name of the function.
- Return type:
str
- get_openai_function_schema() Dict[str, Any] [source]#
Gets the schema of the function from the OpenAI tool schema.
This method extracts and returns the function-specific part of the OpenAI tool schema associated with this function.
- Returns:
- The schema of the function within the OpenAI tool
schema.
- Return type:
Dict[str, Any]
- get_openai_tool_schema() Dict[str, Any] [source]#
Gets the OpenAI tool schema for this function.
This method returns the OpenAI tool schema associated with this function, after validating it to ensure it meets OpenAI’s specifications.
- Returns:
The OpenAI tool schema for this function.
- Return type:
Dict[str, Any]
- get_parameter(param_name: str) Dict[str, Any] [source]#
Gets the schema for a specific parameter from the function schema.
- Parameters:
param_name (str) – The name of the parameter to get the schema.
- Returns:
The schema of the specified parameter.
- Return type:
Dict[str, Any]
- get_paramter_description(param_name: str) str [source]#
Gets the description of a specific parameter from the function schema.
- Parameters:
param_name (str) – The name of the parameter to get the description.
- Returns:
The description of the specified parameter.
- Return type:
str
- property parameters: Dict[str, Any]#
Getter method for the property
parameters
.- Returns:
- the dictionary containing information of
parameters of this function.
- Return type:
Dict[str, Any]
- set_function_description(description: str) None [source]#
Sets the description of the function in the OpenAI tool schema.
- Parameters:
description (str) – The description for the function.
- set_function_name(name: str) None [source]#
Sets the name of the function in the OpenAI tool schema.
- Parameters:
name (str) – The name of the function to set.
- set_openai_function_schema(openai_function_schema: Dict[str, Any]) None [source]#
Sets the schema of the function within the OpenAI tool schema.
- Parameters:
openai_function_schema (Dict[str, Any]) – The function schema to set within the OpenAI tool schema.
- set_openai_tool_schema(schema: Dict[str, Any]) None [source]#
Sets the OpenAI tool schema for this function.
Allows setting a custom OpenAI tool schema for this function.
- Parameters:
schema (Dict[str, Any]) – The OpenAI tool schema to set.
- set_parameter(param_name: str, value: Dict[str, Any])[source]#
Sets the schema for a specific parameter in the function schema.
- Parameters:
param_name (str) – The name of the parameter to set the schema for.
value (Dict[str, Any]) – The schema to set for the parameter.
- set_paramter_description(param_name: str, description: str) None [source]#
Sets the description for a specific parameter in the function schema.
- Parameters:
param_name (str) – The name of the parameter to set the description for.
description (str) – The description for the parameter.
- synthesize_execution_output(args: tuple[Any, ...] | None = None, kwargs: Dict[str, Any] | None = None) Any [source]#
Synthesizes the output of the function based on the provided positional arguments and keyword arguments.
- Parameters:
args (Optional[tuple]) – Positional arguments to pass to the function during synthesis. (default:
None
)kwargs (Optional[Dict[str, Any]]) – Keyword arguments to pass to the function during synthesis. (default:
None
)
- Returns:
- Synthesized output from the function execution. If no
synthesis model is provided, a warning is logged.
- Return type:
Any
- synthesize_openai_tool_schema(max_retries: int | None = None) Dict[str, Any] [source]#
Synthesizes an OpenAI tool schema for the specified function.
This method uses a language model (LLM) to synthesize the OpenAI tool schema for the specified function by first generating a docstring and then creating a schema based on the function’s source code. The schema synthesis and validation process is retried up to max_retries times in case of failure.
- Parameters:
max_retries (Optional[int], optional) – The maximum number of retries for schema synthesis and validation if the process fails. (default:
None
)- Returns:
The synthesis OpenAI tool schema for the function.
- Return type:
Dict[str, Any]
- Raises:
ValueError – If schema synthesis or validation fails after the maximum number of retries, a ValueError is raised, prompting manual schema setting.
- static validate_openai_tool_schema(openai_tool_schema: Dict[str, Any]) None [source]#
Validates the OpenAI tool schema against
ToolAssistantToolsFunction
. This function checks if the providedopenai_tool_schema
adheres to the specifications required by OpenAI’sToolAssistantToolsFunction
. It ensures that the function description and parameters are correctly formatted according to JSON Schema specifications. :param openai_tool_schema: The OpenAI tool schema tovalidate.
- Raises:
ValidationError – If the schema does not comply with the specifications.
SchemaError – If the parameters do not meet JSON Schema reference specifications.
- class camel.toolkits.GithubToolkit(repo_name: str, access_token: str | None = None)[source]#
Bases:
BaseToolkit
A class representing a toolkit for interacting with GitHub repositories.
- This class provides methods for retrieving open issues, retrieving
specific issues, and creating pull requests in a GitHub repository.
- Parameters:
repo_name (str) – The name of the GitHub repository.
access_token (str, optional) – The access token to authenticate with GitHub. If not provided, it will be obtained using the get_github_access_token method.
- create_pull_request(file_path: str, new_content: str, pr_title: str, body: str, branch_name: str) str [source]#
Creates a pull request.
This function creates a pull request in specified repository, which updates a file in the specific path with new content. The pull request description contains information about the issue title and number.
- Parameters:
file_path (str) – The path of the file to be updated in the repository.
new_content (str) – The specified new content of the specified file.
pr_title (str) – The title of the issue that is solved by this pull request.
body (str) – The commit message for the pull request.
branch_name (str) – The name of the branch to create and submit the pull request from.
- Returns:
- A formatted report of whether the pull request was created
successfully or not.
- Return type:
str
- get_all_file_paths(path: str = '') List[str] [source]#
Recursively retrieves all file paths in the GitHub repository.
- Parameters:
path (str) – The repository path to start the traversal from. empty string means starts from the root directory. (default: :obj: “”)
- Returns:
- A list of file paths within the specified directory
structure.
- Return type:
List[str]
- get_github_access_token() str [source]#
Retrieve the GitHub access token from environment variables.
- Returns:
A string containing the GitHub access token.
- Return type:
str
- Raises:
ValueError – If the API key or secret is not found in the environment variables.
- get_issue_content(issue_number: int) str [source]#
Retrieves the content of a specific issue by its number.
- Parameters:
issue_number (int) – The number of the issue to retrieve.
- Returns:
issues content details.
- Return type:
str
- get_issue_list(state: Literal['open', 'closed', 'all'] = 'all') List[Dict[str, object]] [source]#
Retrieves all issues from the GitHub repository.
- Parameters:
state (Literal["open", "closed", "all"]) – The state of pull requests to retrieve. (default: :obj: all) Options are: - “open”: Retrieve only open pull requests. - “closed”: Retrieve only closed pull requests. - “all”: Retrieve all pull requests, regardless of state.
- Returns:
- A list of dictionaries where each
dictionary contains the issue number and title.
- Return type:
List[Dict[str, object]]
- get_pull_request_code(pr_number: int) List[Dict[str, str]] [source]#
Retrieves the code changes of a specific pull request.
- Parameters:
pr_number (int) – The number of the pull request to retrieve.
- Returns:
- A list of dictionaries where each dictionary
contains the file name and the corresponding code changes (patch).
- Return type:
List[Dict[str, str]]
- get_pull_request_comments(pr_number: int) List[Dict[str, str]] [source]#
Retrieves the comments from a specific pull request.
- Parameters:
pr_number (int) – The number of the pull request to retrieve.
- Returns:
- A list of dictionaries where each dictionary
contains the user ID and the comment body.
- Return type:
List[Dict[str, str]]
- get_pull_request_list(state: Literal['open', 'closed', 'all'] = 'all') List[Dict[str, object]] [source]#
Retrieves all pull requests from the GitHub repository.
- Parameters:
state (Literal["open", "closed", "all"]) – The state of pull requests to retrieve. (default: :obj: all) Options are: - “open”: Retrieve only open pull requests. - “closed”: Retrieve only closed pull requests. - “all”: Retrieve all pull requests, regardless of state.
- Returns:
- A list of dictionaries where each dictionary contains the
pull request number and title.
- Return type:
list
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects representing
the functions in the toolkit.
- Return type:
List[FunctionTool]
- class camel.toolkits.GoogleMapsToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for interacting with GoogleMaps API. This class provides methods for validating addresses, retrieving elevation, and fetching timezone information using the Google Maps API.
- get_address_description(address: str | List[str], region_code: str | None = None, locality: str | None = None) str [source]#
Validates an address via Google Maps API, returns a descriptive summary. Validates an address using Google Maps API, returning a summary that includes information on address completion, formatted address, location coordinates, and metadata types that are true for the given address.
- Parameters:
address (Union[str, List[str]]) – The address or components to validate. Can be a single string or a list representing different parts.
region_code (str, optional) – Country code for regional restriction, helps narrow down results. (default:
None
)locality (str, optional) – Restricts validation to a specific locality, e.g., “Mountain View”. (default:
None
)
- Returns:
- Summary of the address validation results, including
information on address completion, formatted address, geographical coordinates (latitude and longitude), and metadata types true for the address.
- Return type:
str
- get_elevation(lat: float, lng: float) str [source]#
Retrieves elevation data for a given latitude and longitude. Uses the Google Maps API to fetch elevation data for the specified latitude and longitude. It handles exceptions gracefully and returns a description of the elevation, including its value in meters and the data resolution.
- Parameters:
lat (float) – The latitude of the location to query.
lng (float) – The longitude of the location to query.
- Returns:
- A description of the elevation at the specified location(s),
including the elevation in meters and the data resolution. If elevation data is not available, a message indicating this is returned.
- Return type:
str
- get_timezone(lat: float, lng: float) str [source]#
Retrieves timezone information for a given latitude and longitude. This function uses the Google Maps Timezone API to fetch timezone data for the specified latitude and longitude. It returns a natural language description of the timezone, including the timezone ID, name, standard time offset, daylight saving time offset, and the total offset from Coordinated Universal Time (UTC).
- Parameters:
lat (float) – The latitude of the location to query.
lng (float) – The longitude of the location to query.
- Returns:
- A descriptive string of the timezone information,
including the timezone ID and name, standard time offset, daylight saving time offset, and total offset from UTC.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- class camel.toolkits.GoogleScholarToolkit(author_identifier: str, is_author_name: bool = False, use_free_proxies: bool = False, proxy_http: str | None = None, proxy_https: str | None = None)[source]#
Bases:
BaseToolkit
A toolkit for retrieving information about authors and their publications from Google Scholar.
- author_identifier#
The author’s Google Scholar URL or name of the author to search for.
- Type:
Union[str, None]
- is_author_name#
Flag to indicate if the identifier is a name. (default:
False
)- Type:
bool
- scholarly#
The scholarly module for querying Google Scholar.
- Type:
module
- author#
Cached author details, allowing manual assignment if desired.
- Type:
Optional[Dict[str, Any]]
- property author: Dict[str, Any]#
Getter for the author attribute, fetching details if not cached.
- Returns:
- A dictionary containing author details. If no data
is available, returns an empty dictionary.
- Return type:
Dict[str, Any]
- get_author_detailed_info() dict [source]#
Retrieves detailed information about the author.
- Returns:
- A dictionary containing detailed information about the
author.
- Return type:
dict
- get_author_publications() List[str] [source]#
Retrieves the titles of the author’s publications.
- Returns:
A list of publication titles authored by the author.
- Return type:
List[str]
- get_full_paper_content_by_link(pdf_url: str) str | None [source]#
Retrieves the full paper content from a given PDF URL using the arxiv2text tool.
- Parameters:
pdf_url (str) – The URL of the PDF file.
- Returns:
- The full text extracted from the PDF, or None if
an error occurs.
- Return type:
Optional[str]
- get_publication_by_title(publication_title: str) dict | None [source]#
Retrieves detailed information about a specific publication by its title. Note that this method cannot retrieve the full content of the paper.
- Parameters:
publication_title (str) – The title of the publication to search for.
- Returns:
- A dictionary containing detailed information about
the publication if found; otherwise, None.
- Return type:
Optional[dict]
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- class camel.toolkits.HumanToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for human interaction.
- ask_human_via_console(question: str) str [source]#
Ask a question to the human via the console.
- Parameters:
question (str) – The question to ask the human.
- Returns:
The answer from the human.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- class camel.toolkits.LinkedInToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for LinkedIn operations.
This class provides methods for creating a post, deleting a post, and retrieving the authenticated user’s profile information.
- create_post(text: str) dict [source]#
Creates a post on LinkedIn for the authenticated user.
- Parameters:
text (str) – The content of the post to be created.
- Returns:
- A dictionary containing the post ID and the content of
the post. If the post creation fails, the values will be None.
- Return type:
dict
- Raises:
Exception – If the post creation fails due to an error response from LinkedIn API.
- delete_post(post_id: str) str [source]#
Deletes a LinkedIn post with the specified ID for an authorized user.
This function sends a DELETE request to the LinkedIn API to delete a post with the specified ID. Before sending the request, it prompts the user to confirm the deletion.
- Parameters:
post_id (str) – The ID of the post to delete.
- Returns:
- A message indicating the result of the deletion. If the
deletion was successful, the message includes the ID of the deleted post. If the deletion was not successful, the message includes an error message.
- Return type:
str
- get_profile(include_id: bool = False) dict [source]#
Retrieves the authenticated user’s LinkedIn profile info.
This function sends a GET request to the LinkedIn API to retrieve the authenticated user’s profile information. Optionally, it also returns the user’s LinkedIn ID.
- Parameters:
include_id (bool) – Whether to include the LinkedIn profile ID in the response.
- Returns:
- A dictionary containing the user’s LinkedIn profile
information. If include_id is True, the dictionary will also include the profile ID.
- Return type:
dict
- Raises:
Exception – If the profile retrieval fails due to an error response from LinkedIn API.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- class camel.toolkits.MathToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for mathematical operations.
This class provides methods for basic mathematical operations such as addition, subtraction, multiplication, division, and rounding.
- add(a: float, b: float) float [source]#
Adds two numbers.
- Parameters:
a (float) – The first number to be added.
b (float) – The second number to be added.
- Returns:
The sum of the two numbers.
- Return type:
float
- divide(a: float, b: float, decimal_places: int = 2) float [source]#
Divides two numbers.
- Parameters:
a (float) – The dividend in the division.
b (float) – The divisor in the division.
decimal_places (int, optional) – The number of decimal places to round to. Defaults to 2.
- Returns:
The result of dividing
a
byb
.- Return type:
float
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- multiply(a: float, b: float, decimal_places: int = 2) float [source]#
Multiplies two numbers.
- Parameters:
a (float) – The multiplier in the multiplication.
b (float) – The multiplicand in the multiplication.
decimal_places (int, optional) – The number of decimal places to round to. Defaults to 2.
- Returns:
The product of the two numbers.
- Return type:
float
- round(a: float, decimal_places: int = 0) float [source]#
Rounds a number to a specified number of decimal places.
- Parameters:
a (float) – The number to be rounded.
decimal_places (int, optional) – The number of decimal places to round to. Defaults to 0.
- Returns:
The rounded number.
- Return type:
float
- class camel.toolkits.MeshyToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for 3D model generation using Meshy.
This class provides methods that handle text/image to 3D model generation using Meshy.
Call the generate_3d_model_complete method to generate a refined 3D model.
Ref: https://docs.meshy.ai/api-text-to-3d-beta#create-a-text-to-3d-preview-task
- generate_3d_model_complete(prompt: str, art_style: str, negative_prompt: str) Dict[str, Any] [source]#
Generates a complete 3D model by handling preview and refinement stages
- Parameters:
prompt (str) – Description of the object.
art_style (str) – Art style for the 3D model.
negative_prompt (str) – What the model should not look like.
- Returns:
The final refined 3D model response.
- Return type:
Dict[str, Any]
- generate_3d_preview(prompt: str, art_style: str, negative_prompt: str) Dict[str, Any] [source]#
Generates a 3D preview using the Meshy API.
- Parameters:
prompt (str) – Description of the object.
art_style (str) – Art style for the 3D model.
negative_prompt (str) – What the model should not look like.
- Returns:
- The result property of the response contains the
task id of the newly created Text to 3D task.
- Return type:
Dict[str, Any]
- get_task_status(task_id: str) Dict[str, Any] [source]#
Retrieves the status or result of a specific 3D model generation task using the Meshy API.
- Parameters:
task_id (str) – The ID of the task to retrieve.
- Returns:
The response from the Meshy API.
- Return type:
Dict[str, Any]
- refine_3d_model(preview_task_id: str) Dict[str, Any] [source]#
Refines a 3D model using the Meshy API.
- Parameters:
preview_task_id (str) – The task ID of the preview to refine.
- Returns:
The response from the Meshy API.
- Return type:
Dict[str, Any]
- wait_for_task_completion(task_id: str, polling_interval: int = 10, timeout: int = 3600) Dict[str, Any] [source]#
Waits for a task to complete by polling its status.
- Parameters:
task_id (str) – The ID of the task to monitor.
polling_interval (int) – Seconds to wait between status checks. (default:
10
)timeout (int) – Maximum seconds to wait before timing out. (default:
3600
)
- Returns:
Final response from the API when task completes.
- Return type:
Dict[str, Any]
- Raises:
TimeoutError – If task doesn’t complete within timeout period.
RuntimeError – If task fails or is canceled.
- class camel.toolkits.NotionToolkit(notion_token: str | None = None)[source]#
Bases:
BaseToolkit
A toolkit for retrieving information from the user’s notion pages.
- notion_token#
The notion_token used to interact with notion APIs. (default:
None
)- Type:
Optional[str], optional
- notion_client#
The notion module for interacting with the notion APIs.
- Type:
module
- get_notion_block_text_content(block_id: str) str [source]#
Retrieves the text content of a Notion block.
- Parameters:
block_id (str) – The ID of the Notion block to retrieve.
- Returns:
- The text content of a Notion block, containing all
the sub blocks.
- Return type:
str
- get_text_from_block(block: dict) str [source]#
Extracts plain text from a Notion block based on its type.
- Parameters:
block (dict) – A dictionary representing a Notion block.
- Returns:
A string containing the extracted plain text and block type.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- class camel.toolkits.OpenAPIToolkit[source]#
Bases:
object
A class representing a toolkit for interacting with OpenAPI APIs.
This class provides methods for interacting with APIs based on OpenAPI specifications. It dynamically generates functions for each API operation defined in the OpenAPI specification, allowing users to make HTTP requests to the API endpoints.
- apinames_filepaths_to_funs_schemas(apinames_filepaths: List[Tuple[str, str]]) Tuple[List[Callable], List[Dict[str, Any]]] [source]#
Combines functions and schemas from multiple OpenAPI specifications, using API names as keys.
This function iterates over tuples of API names and OpenAPI spec file paths, parsing each spec to generate callable functions and schema dictionaries, all organized by API name.
Args: apinames_filepaths (List[Tuple[str, str]]): A list of tuples, where
each tuple consists of: - The API name (str) as the first element. - The file path (str) to the API’s OpenAPI specification file as
the second element.
- Returns:
- Tuple[List[Callable], List[Dict[str, Any]]]:: one of callable
functions for API operations, and another of dictionaries representing the schemas from the specifications.
- generate_apinames_filepaths() List[Tuple[str, str]] [source]#
Generates a list of tuples containing API names and their corresponding file paths.
This function iterates over the OpenAPIName enum, constructs the file path for each API’s OpenAPI specification file, and appends a tuple of the API name and its file path to the list. The file paths are relative to the ‘open_api_specs’ directory located in the same directory as this script.
- Returns:
- A list of tuples where each tuple contains
two elements. The first element of each tuple is a string representing the name of an API, and the second element is a string that specifies the file path to that API’s OpenAPI specification file.
- Return type:
List[Tuple[str, str]]
- generate_openapi_funcs(api_name: str, openapi_spec: Dict[str, Any]) List[Callable] [source]#
Generates a list of Python functions based on OpenAPI specification.
This function dynamically creates a list of callable functions that represent the API operations defined in an OpenAPI specification document. Each function is designed to perform an HTTP request corresponding to an API operation (e.g., GET, POST) as defined in the specification. The functions are decorated with openapi_function_decorator, which configures them to construct and send the HTTP requests with appropriate parameters, headers, and body content.
- Parameters:
api_name (str) – The name of the API, used to prefix generated function names.
openapi_spec (Dict[str, Any]) – The OpenAPI specification as a dictionary.
- Returns:
- A list containing the generated functions. Each
function, when called, will make an HTTP request according to its corresponding API operation defined in the OpenAPI specification.
- Return type:
List[Callable]
- Raises:
ValueError – If the OpenAPI specification does not contain server information, which is necessary for determining the base URL for the API requests.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- openapi_function_decorator(api_name: str, base_url: str, path: str, method: str, openapi_security: List[Dict[str, Any]], sec_schemas: Dict[str, Dict[str, Any]], operation: Dict[str, Any]) Callable [source]#
Decorate a function to make HTTP requests based on OpenAPI specification details.
This decorator dynamically constructs and executes an API request based on the provided OpenAPI operation specifications, security requirements, and parameters. It supports operations secured with apiKey type security schemes and automatically injects the necessary API keys from environment variables. Parameters in path, query, header, and cookie are also supported.
- Parameters:
api_name (str) – The name of the API, used to retrieve API key names and URLs from the configuration.
base_url (str) – The base URL for the API.
path (str) – The path for the API endpoint, relative to the base URL.
method (str) – The HTTP method (e.g., ‘get’, ‘post’) for the request.
openapi_security (List[Dict[str, Any]]) – The global security definitions as specified in the OpenAPI specs.
sec_schemas (Dict[str, Dict[str, Any]]) – Detailed security schemes.
operation (Dict[str, Any]) – A dictionary containing the OpenAPI operation details, including parameters and request body definitions.
- Returns:
- A decorator that, when applied to a function, enables the
function to make HTTP requests based on the provided OpenAPI operation details.
- Return type:
Callable
- Raises:
TypeError – If the security requirements include unsupported types.
ValueError – If required API keys are missing from environment variables or if the content type of the request body is unsupported.
- openapi_spec_to_openai_schemas(api_name: str, openapi_spec: Dict[str, Any]) List[Dict[str, Any]] [source]#
Convert OpenAPI specification to OpenAI schema format.
This function iterates over the paths and operations defined in an OpenAPI specification, filtering out deprecated operations. For each operation, it constructs a schema in a format suitable for OpenAI, including operation metadata such as function name, description, parameters, and request bodies. It raises a ValueError if an operation lacks a description or summary.
- Parameters:
api_name (str) – The name of the API, used to prefix generated function names.
openapi_spec (Dict[str, Any]) – The OpenAPI specification as a dictionary.
- Returns:
- A list of dictionaries, each representing a
function in the OpenAI schema format, including details about the function’s name, description, and parameters.
- Return type:
List[Dict[str, Any]]
- Raises:
ValueError – If an operation in the OpenAPI specification does not have a description or summary.
Note
This function assumes that the OpenAPI specification follows the 3.0+ format.
- Reference:
- parse_openapi_file(openapi_spec_path: str) Dict[str, Any] | None [source]#
Load and parse an OpenAPI specification file.
This function utilizes the prance.ResolvingParser to parse and resolve the given OpenAPI specification file, returning the parsed OpenAPI specification as a dictionary.
- Parameters:
openapi_spec_path (str) – The file path or URL to the OpenAPI specification.
- Returns:
- The parsed OpenAPI specification
as a dictionary.
None
if the package is not installed.
- Return type:
Optional[Dict[str, Any]]
- class camel.toolkits.OpenBBToolkit[source]#
Bases:
BaseToolkit
A toolkit for accessing financial data and analysis through OpenBB Platform.
This toolkit provides methods for retrieving and analyzing financial market data, including stocks, ETFs, cryptocurrencies, economic indicators, and more through the OpenBB Platform SDK. For credential configuration, please refer to the OpenBB documentation https://my.openbb.co/app/platform/credentials .
- get_available_indicators(provider: Literal['econdb', 'imf'] = 'econdb') List [source]#
Get list of available economic indicators.
- Parameters:
provider (Literal["econdb", "imf"]) – Data provider. (default:
econdb
)- Returns:
Available indicators.
- Return type:
List
- get_available_indices(provider: Literal['fmp', 'yfinance'] = 'fmp') List [source]#
Get list of available market indices.
- Parameters:
provider (Literal["fmp", "yfinance"]) – Data provider. (default:
fmp
)- Returns:
Available indices.
- Return type:
List
- get_company_profile(symbol: str, provider: Literal['fmp', 'intrinio', 'yfinance'] = 'fmp') List [source]#
Get company profile information.
- Parameters:
symbol (str) – Stock symbol (e.g., ‘AAPL’ for Apple Inc.).
provider (Literal["fmp", "intrinio", "yfinance"]) – Data provider. (default:
fmp
)
- Returns:
Company profile.
- Return type:
List
- get_dividend_calendar(start_date: str | None = None, end_date: str | None = None) List [source]#
Get dividend calendar with optional yield calculations.
- Parameters:
start_date (Optional[str]) – Start date in YYYY-MM-DD format. (default:
None
)end_date (Optional[str]) – End date in YYYY-MM-DD format. (default:
None
)
- Returns:
Dividend calendar.
- Return type:
List
- get_earnings_calendar(start_date: str | None = None, end_date: str | None = None) List [source]#
Get company earnings calendar with filtering and sorting options.
- Parameters:
start_date (Optional[str]) – Start date in YYYY-MM-DD format. (default:
None
)end_date (Optional[str]) – End date in YYYY-MM-DD format. (default:
None
)
- Returns:
Earnings calendar.
- Return type:
List
- get_economic_calendar(provider: Literal['fmp', 'tradingeconomics'] = 'fmp', start_date: str | None = None, end_date: str | None = None) List [source]#
Get economic calendar events.
- Parameters:
provider (Literal["fmp", "tradingeconomics"]) – Data provider. (default:
fmp
)start_date (Optional[str]) – Start date in YYYY-MM-DD format. (default:
None
)end_date (Optional[str]) – End date in YYYY-MM-DD format. (default:
None
)
- Returns:
Economic calendar.
- Return type:
List
- get_financial_attributes(symbol: str, tag: str, frequency: Literal['daily', 'weekly', 'monthly', 'quarterly', 'yearly'] = 'yearly') List [source]#
Get historical values for a specific financial attribute.
- Parameters:
symbol (str) – Stock symbol (e.g., ‘AAPL’ for Apple Inc.).
tag (str) – Financial attribute tag (use search_financial_attributes to find tags).
(Literal["daily" (frequency) – “yearly”]): Data frequency, “daily”, “weekly”, “monthly”, “quarterly”, “yearly”. (default:
yearly
)"weekly" – “yearly”]): Data frequency, “daily”, “weekly”, “monthly”, “quarterly”, “yearly”. (default:
yearly
)"monthly" – “yearly”]): Data frequency, “daily”, “weekly”, “monthly”, “quarterly”, “yearly”. (default:
yearly
)"quarterly" – “yearly”]): Data frequency, “daily”, “weekly”, “monthly”, “quarterly”, “yearly”. (default:
yearly
)
- :param“yearly”]): Data frequency, “daily”, “weekly”, “monthly”,
“quarterly”, “yearly”. (default:
yearly
)
- Returns:
Historical values.
- Return type:
List
- get_financial_metrics(symbol: str, provider: Literal['fmp', 'intrinio', 'yfinance'] = 'fmp', period: Literal['annual', 'quarter'] = 'annual', limit: int = 5) List [source]#
Get company financial metrics and ratios.
- Parameters:
symbol (str) – Stock symbol (e.g., ‘AAPL’ for Apple Inc.).
provider (Literal["fmp", "intrinio", "yfinance"]) – Data source. (default:
fmp
)period (Literal["annual", "quarter"]) – Reporting period, “annual”: Annual metrics, “quarter”: Quarterly metrics. (default:
annual
)limit (int) – Number of periods to return. (default:
5
)
- Returns:
Financial metric.
- Return type:
List
- get_financial_statement(symbol: str, provider: Literal['fmp', 'intrinio', 'polygon', 'yfinance'] = 'fmp', statement_type: Literal['balance', 'income', 'cash'] = 'balance', period: Literal['annual', 'quarter'] = 'annual', limit: int = 5) List [source]#
Get company financial statements.
Access balance sheet, income statement, or cash flow statement data. Data availability and field names vary by provider and company type.
- Parameters:
symbol (str) – Stock symbol (e.g., ‘AAPL’ for Apple Inc.).
provider (Literal["fmp", "intrinio", "polygon", "yfinance"]) – Data provider. (default:
fmp
)statement_type (Literal["balance", "income", "cash"]) – Type of financial statement, “balance”: Balance sheet, “income”: Income statement, “cash”: Cash flow statement. (default:
balance
)period (Literal["annual", "quarter"]) – Reporting period, “annual”: Annual reports, “quarter”: Quarterly reports. (default:
annual
)limit (int) – Number of periods to return. (default:
5
)
- Returns:
Financial statement data.
- Return type:
List
- get_historical_data(symbol: str, provider: Literal['fmp', 'polygon', 'tiingo', 'yfinance'] = 'fmp', asset_type: Literal['equity', 'currency', 'crypto'] = 'equity', start_date: str | None = None, end_date: str | None = None, interval: Literal['1m', '5m', '15m', '30m', '1h', '4h', '1d'] = '1d') List [source]#
Retrieves historical market data from OpenBB Platform providers.
- Parameters:
symbol (str) – Stock symbol (e.g., ‘AAPL’ for Apple Inc.).
provider (Literal["fmp", "polygon", "tiingo", "yfinance"]) – Data source. (default:
fmp
)asset_type (Literal["equity", "currency", "crypto"]) – Asset type. (default:
equity
)start_date – Start date in YYYY-MM-DD format. If None, uses provider’s default lookback. (default:
None
)end_date – End date in YYYY-MM-DD format. If None, uses current date. (default:
None
)interval – Data frequency/timeframe. (default:
1d
)
- Returns:
Historical market data.
- Return type:
List
- get_indicator_data(symbol: str, country: str, provider: Literal['econdb', 'imf'] = 'econdb') List [source]#
Get detailed metadata for an economic indicator.
- Parameters:
symbol (str) – Stock symbol (e.g., ‘AAPL’ for Apple Inc.).
country (str) – Country code (e.g., ‘US’ for United States).
provider (Literal["econdb", "imf"]) – Data provider. (default:
econdb
)
- Returns:
Indicator data.
- Return type:
List
- get_ipo_calendar(start_date: str | None = None, end_date: str | None = None) List [source]#
Get IPO/SPO calendar with comprehensive filtering options.
- Parameters:
start_date (Optional[str]) – Start date in YYYY-MM-DD format. (default:
None
)end_date (Optional[str]) – End date in YYYY-MM-DD format. (default:
None
)
- Returns:
IPO/SPO calendar.
- Return type:
List
- get_market_data(category: Literal['gainers', 'losers', 'active'] = 'active') List [source]#
Get market movers data.
- Parameters:
category (Literal["gainers", "losers", "active"]) – Type of market data. Must be ‘gainers’, ‘losers’, or ‘active’. (default:
active
)- Returns:
Market movers data.
- Return type:
List
- get_stock_quote(symbol: str, provider: Literal['fmp', 'intrinio', 'yfinance'] = 'fmp') List [source]#
Get current stock quote for a given symbol.
- Parameters:
symbol (str) – Stock symbol (e.g., ‘AAPL’ for Apple Inc.)
provider (Literal["fmp", "intrinio", "yfinance"]) – Data source. (default:
fmp
)
- Returns:
Stock quote data in requested format
- Return type:
List
- get_tools() List[FunctionTool] [source]#
Returns a list of available OpenBB financial tools.
- Returns:
List of available tools.
- Return type:
List[FunctionTool]
- screen_market(provider: Literal['fmp', 'yfinance'] = 'fmp', country: str | None = None, exchange: str | None = None, sector: str | None = None, industry: str | None = None, mktcap_min: float | None = None, mktcap_max: float | None = None, beta_min: float | None = None, beta_max: float | None = None) List [source]#
Screen stocks based on market and fundamental criteria.
- Parameters:
provider (Literal["fmp", "yfinance"]) – Data provider. (default:
fmp
)country (Optional[str]) – Two-letter ISO country code (e.g., ‘US’, ‘IN’, ‘CN’). (default:
None
)exchange (Optional[str]) – Stock exchange code (e.g., ‘NYSE’, ‘AMEX’, ‘NSE’). (default:
None
)sector (Optional[str]) – Market sector (e.g., ‘Financial Services’, ‘Healthcare). (default:
None
)industry (Optional[str]) – Industry within sector (e.g., ‘Banks—Regional’,’Drug Manufacturers’). (default:
None
)mktcap_min (Optional[float]) – Minimum market cap in USD. (default:
None
)mktcap_max (Optional[float]) – Maximum market cap in USD. (default:
None
)beta_min (Optional[float]) – Minimum beta value. (default:
None
)beta_max (Optional[float]) – Maximum beta value. (default:
None
)
- Returns:
Screened stocks.
- Return type:
List
- search_equity(query: str, provider: Literal['intrinio', 'sec'] = 'sec') List [source]#
Search for equity symbols and company information.
For SEC provider, an empty query (“”) returns the complete list of companies sorted by market cap.
- Parameters:
query (str) – Search query (company name or symbol), use “” for complete SEC list.
provider (Literal["intrinio", "sec"]) – Data provider. Available options: - sec: SEC EDGAR Database (sorted by market cap) - intrinio: Intrinio Financial Data
- Returns:
Search results.
- Return type:
List
- search_etf(query: str, provider: Literal['fmp', 'intrinio'] = 'fmp') List [source]#
Search for ETF information.
- Parameters:
query (str) – Search query (ETF name or symbol).
provider (Literal["fmp", "intrinio"]) – Data provider. (default:
fmp
)
- Returns:
ETF search results.
- Return type:
List
- search_filings(symbol: str, provider: Literal['fmp', 'intrinio', 'sec'] = 'sec', form_type: str | None = None) List [source]#
Search for SEC filings by CIK or ticker symbol.
- Parameters:
symbol (str) – Symbol to get data for (e.g., “MAXD”).
provider (Literal["fmp", "intrinio", "sec"]) – Data provider. (default:
sec
)form_type (Optional[str]) – Filter by form type. Check the data provider for available types. Multiple comma separated items allowed for provider(s): sec. (default:
None
)
- Returns:
Filing search results.
- Return type:
List
- class camel.toolkits.RedditToolkit(retries: int = 3, delay: int = 0)[source]#
Bases:
BaseToolkit
A class representing a toolkit for Reddit operations.
This toolkit provides methods to interact with the Reddit API, allowing users to collect top posts, perform sentiment analysis on comments, and track keyword discussions across multiple subreddits.
- retries#
Number of retries for API requests in case of failure.
- Type:
int
- delay#
Delay between retries in seconds.
- Type:
int
- reddit#
An instance of the Reddit client.
- Type:
Reddit
- collect_top_posts(subreddit_name: str, post_limit: int = 5, comment_limit: int = 5) List[Dict[str, Any]] | str [source]#
Collects the top posts and their comments from a specified subreddit.
- Parameters:
subreddit_name (str) – The name of the subreddit to collect posts from.
post_limit (int) – The maximum number of top posts to collect. Defaults to 5.
comment_limit (int) – The maximum number of top comments to collect per post. Defaults to 5.
- Returns:
- A list of dictionaries, each
containing the post title and its top comments if success. String warming if credentials are not set.
- Return type:
Union[List[Dict[str, Any]], str]
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects for the
toolkit methods.
- Return type:
List[FunctionTool]
- perform_sentiment_analysis(data: List[Dict[str, Any]]) List[Dict[str, Any]] [source]#
Performs sentiment analysis on the comments collected from Reddit posts.
- Parameters:
data (List[Dict[str, Any]]) – A list of dictionaries containing Reddit post data and comments.
- Returns:
- The original data with an added ‘Sentiment
Score’ for each comment.
- Return type:
List[Dict[str, Any]]
- track_keyword_discussions(subreddits: List[str], keywords: List[str], post_limit: int = 10, comment_limit: int = 10, sentiment_analysis: bool = False) List[Dict[str, Any]] | str [source]#
Tracks discussions about specific keywords in specified subreddits.
- Parameters:
subreddits (List[str]) – A list of subreddit names to search within.
keywords (List[str]) – A list of keywords to track in the subreddit discussions.
post_limit (int) – The maximum number of top posts to collect per subreddit. Defaults to 10.
comment_limit (int) – The maximum number of top comments to collect per post. Defaults to 10.
sentiment_analysis (bool) – If True, performs sentiment analysis on the comments. Defaults to False.
- Returns:
- A list of dictionaries
containing the subreddit name, post title, comment body, and upvotes for each comment that contains the specified keywords if success. String warming if credentials are not set.
- Return type:
Union[List[Dict[str, Any]], str]
- class camel.toolkits.RetrievalToolkit(auto_retriever: AutoRetriever | None = None)[source]#
Bases:
BaseToolkit
A class representing a toolkit for information retrieval.
This class provides methods for retrieving information from a local vector storage system based on a specified query.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- information_retrieval(query: str, contents: str | List[str], top_k: int = 1, similarity_threshold: float = 0.7) str [source]#
Retrieves information from a local vector storage based on the specified query. This function connects to a local vector storage system and retrieves relevant information by processing the input query. It is essential to use this function when the answer to a question requires external knowledge sources.
- Parameters:
query (str) – The question or query for which an answer is required.
contents (Union[str, List[str]]) – Local file paths, remote URLs or string contents.
top_k (int, optional) – The number of top results to return during retrieve. Must be a positive integer. Defaults to DEFAULT_TOP_K_RESULTS.
similarity_threshold (float, optional) – The similarity threshold for filtering results. Defaults to DEFAULT_SIMILARITY_THRESHOLD.
- Returns:
- The information retrieved in response to the query, aggregated
and formatted as a string.
- Return type:
str
Example
# Retrieve information about CAMEL AI. information_retrieval(query = “How to contribute to CAMEL AI?”,
contents=”camel-ai/camel”)
- class camel.toolkits.SearchToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for web search.
This class provides methods for searching information on the web using search engines like Google, DuckDuckGo, Wikipedia and Wolfram Alpha, Brave.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- query_wolfram_alpha(query: str, is_detailed: bool = False) str | Dict[str, Any] [source]#
Queries Wolfram|Alpha and returns the result. Wolfram|Alpha is an answer engine developed by Wolfram Research. It is offered as an online service that answers factual queries by computing answers from externally sourced data.
- Parameters:
query (str) – The query to send to Wolfram Alpha.
is_detailed (bool) – Whether to include additional details including step by step information in the result. (default:
False
)
- Returns:
- The result from Wolfram Alpha.
Returns a string if is_detailed is False, otherwise returns a dictionary with detailed information.
- Return type:
Union[str, Dict[str, Any]]
- search_brave(q: str, country: str = 'US', search_lang: str = 'en', ui_lang: str = 'en-US', count: int = 20, offset: int = 0, safesearch: str = 'moderate', freshness: str | None = None, text_decorations: bool = True, spellcheck: bool = True, result_filter: str | None = None, goggles_id: str | None = None, units: str | None = None, extra_snippets: bool | None = None, summary: bool | None = None) Dict[str, Any] [source]#
This function queries the Brave search engine API and returns a dictionary, representing a search result. See https://api.search.brave.com/app/documentation/web-search/query for more details.
- Parameters:
q (str) – The user’s search query term. Query cannot be empty. Maximum of 400 characters and 50 words in the query.
country (str) – The search query country where results come from. The country string is limited to 2 character country codes of supported countries. For a list of supported values, see Country Codes. (default: :obj:`US `)
search_lang (str) – The search language preference. The 2 or more character language code for which search results are provided. For a list of possible values, see Language Codes.
ui_lang (str) – User interface language preferred in response. Usually of the format ‘<language_code>-<country_code>’. For more, see RFC 9110. For a list of supported values, see UI Language Codes.
count (int) – The number of search results returned in response. The maximum is 20. The actual number delivered may be less than requested. Combine this parameter with offset to paginate search results.
offset (int) – The zero based offset that indicates number of search results per page (count) to skip before returning the result. The maximum is 9. The actual number delivered may be less than requested based on the query. In order to paginate results use this parameter together with count. For example, if your user interface displays 20 search results per page, set count to 20 and offset to 0 to show the first page of results. To get subsequent pages, increment offset by 1 (e.g. 0, 1, 2). The results may overlap across multiple pages.
safesearch (str) –
Filters search results for adult content. The following values are supported: - ‘off’: No filtering is done. - ‘moderate’: Filters explicit content, like images and videos,
but allows adult domains in the search results.
’strict’: Drops all adult content from search results.
freshness (Optional[str]) –
Filters search results by when they were discovered: - ‘pd’: Discovered within the last 24 hours. - ‘pw’: Discovered within the last 7 Days. - ‘pm’: Discovered within the last 31 Days. - ‘py’: Discovered within the last 365 Days. - ‘YYYY-MM-DDtoYYYY-MM-DD’: Timeframe is also supported by
specifying the date range e.g. ‘2022-04-01to2022-07-30’.
text_decorations (bool) – Whether display strings (e.g. result snippets) should include decoration markers (e.g. highlighting characters).
spellcheck (bool) – Whether to spellcheck provided query. If the spellchecker is enabled, the modified query is always used for search. The modified query can be found in altered key from the query response model.
result_filter (Optional[str]) – A comma delimited string of result types to include in the search response. Not specifying this parameter will return back all result types in search response where data is available and a plan with the corresponding option is subscribed. The response always includes query and type to identify any query modifications and response type respectively. Available result filter values are: - ‘discussions’ - ‘faq’ - ‘infobox’ - ‘news’ - ‘query’ - ‘summarizer’ - ‘videos’ - ‘web’ - ‘locations’
goggles_id (Optional[str]) – Goggles act as a custom re-ranking on top of Brave’s search index. For more details, refer to the Goggles repository.
units (Optional[str]) – The measurement units. If not provided, units are derived from search country. Possible values are: - ‘metric’: The standardized measurement system - ‘imperial’: The British Imperial system of units.
extra_snippets (Optional[bool]) – A snippet is an excerpt from a page you get as a result of the query, and extra_snippets allow you to get up to 5 additional, alternative excerpts. Only available under Free AI, Base AI, Pro AI, Base Data, Pro Data and Custom plans.
summary (Optional[bool]) – This parameter enables summary key generation in web search results. This is required for summarizer to be enabled.
- Returns:
A dictionary representing a search result.
- Return type:
Dict[str, Any]
- search_duckduckgo(query: str, source: str = 'text', max_results: int = 5) List[Dict[str, Any]] [source]#
Use DuckDuckGo search engine to search information for the given query.
This function queries the DuckDuckGo API for related topics to the given search term. The results are formatted into a list of dictionaries, each representing a search result.
- Parameters:
query (str) – The query to be searched.
source (str) – The type of information to query (e.g., “text”, “images”, “videos”). Defaults to “text”.
max_results (int) – Max number of results, defaults to 5.
- Returns:
- A list of dictionaries where each dictionary
represents a search result.
- Return type:
List[Dict[str, Any]]
- search_google(query: str, num_result_pages: int = 5) List[Dict[str, Any]] [source]#
Use Google search engine to search information for the given query.
- Parameters:
query (str) – The query to be searched.
num_result_pages (int) – The number of result pages to retrieve.
- Returns:
A list of dictionaries where each dictionary represents a website.
Each dictionary contains the following keys: - ‘result_id’: A number in order. - ‘title’: The title of the website. - ‘description’: A brief description of the website. - ‘long_description’: More detail of the website. - ‘url’: The URL of the website.
Example: {
’result_id’: 1, ‘title’: ‘OpenAI’, ‘description’: ‘An organization focused on ensuring that artificial general intelligence benefits all of humanity.’, ‘long_description’: ‘OpenAI is a non-profit artificial intelligence research company. Our goal is to advance digital intelligence in the way that is most likely to benefit humanity as a whole’, ‘url’: ‘https://www.openai.com’
}
title, description, url of a website.
- Return type:
List[Dict[str, Any]]
- search_linkup(query: str, depth: Literal['standard', 'deep'] = 'standard', output_type: Literal['searchResults', 'sourcedAnswer', 'structured'] = 'searchResults', structured_output_schema: Type[BaseModel] | str | None = None) Dict[str, Any] [source]#
Search for a query in the Linkup API and return results in various formats.
- Parameters:
query (str) – The search query.
depth (Literal["standard", "deep"]) – The depth of the search. “standard” for a straightforward search, “deep” for a more comprehensive search.
(Literal["searchResults" (output_type) – “structured”]): The type of output: - “searchResults” for raw search results, - “sourcedAnswer” for an answer with supporting sources, - “structured” for output based on a provided schema.
"sourcedAnswer" – “structured”]): The type of output: - “searchResults” for raw search results, - “sourcedAnswer” for an answer with supporting sources, - “structured” for output based on a provided schema.
- :param“structured”]): The type of output:
“searchResults” for raw search results,
“sourcedAnswer” for an answer with supporting sources,
“structured” for output based on a provided schema.
- Parameters:
structured_output_schema (Union[Type[BaseModel], str, None]) – If output_type is “structured”,specify the schema of the output. Can be a Pydantic BaseModel or a JSON schema string.
- Returns:
- A dictionary representing the search result. The
structure depends on the output_type. If an error occurs, returns an error message.
- Return type:
Dict[str, Any]
- search_wiki(entity: str) str [source]#
- Search the entity in WikiPedia and return the summary of the
required page, containing factual information about the given entity.
- Parameters:
entity (str) – The entity to be searched.
- Returns:
- The search result. If the page corresponding to the entity
exists, return the summary of this entity in a string.
- Return type:
str
- tavily_search(query: str, num_results: int = 5, **kwargs) List[Dict[str, Any]] [source]#
Use Tavily Search API to search information for the given query.
- Parameters:
query (str) – The query to be searched.
num_results (int) – The number of search results to retrieve (default is 5).
**kwargs –
Additional optional parameters supported by Tavily’s API: - search_depth (str): “basic” or “advanced” search depth. - topic (str): The search category, e.g., “general” or “news.” - days (int): Time frame in days for news-related searches. - max_results (int): Max number of results to return
(overrides num_results).
See https://docs.tavily.com/docs/python-sdk/tavily-search/ api-reference for details.
- Returns:
- A list of dictionaries representing search
results. Each dictionary contains: - ‘result_id’ (int): The result’s index. - ‘title’ (str): The title of the result. - ‘description’ (str): A brief description of the result. - ‘long_description’ (str): Detailed information, if available. - ‘url’ (str): The URL of the result. - ‘content’ (str): Relevant content from the search result. - ‘images’ (list): A list of related images (if
include_images is True).
’published_date’ (str): Publication date for news topics (if available).
- Return type:
List[Dict[str, Any]]
- class camel.toolkits.SlackToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for Slack operations.
This class provides methods for Slack operations such as creating a new channel, joining an existing channel, leaving a channel.
- create_slack_channel(name: str, is_private: bool | None = True) str [source]#
Creates a new slack channel, either public or private.
- Parameters:
name (str) – Name of the public or private channel to create.
is_private (bool, optional) – Whether to create a private channel instead of a public one. Defaults to True.
- Returns:
- JSON string containing information about Slack
channel created.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel information.
- delete_slack_message(time_stamp: str, channel_id: str) str [source]#
Delete a message to a Slack channel.
- Parameters:
time_stamp (str) – Timestamp of the message to be deleted.
channel_id (str) – The ID of the Slack channel to delete message.
- Returns:
- A confirmation message indicating whether the message
was delete successfully or an error message.
- Return type:
str
- Raises:
SlackApiError – If an error occurs while sending the message.
- get_slack_channel_information() str [source]#
- Retrieve Slack channels and return relevant information in JSON
format.
- Returns:
JSON string containing information about Slack channels.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel information.
- get_slack_channel_message(channel_id: str) str [source]#
Retrieve messages from a Slack channel.
- Parameters:
channel_id (str) – The ID of the Slack channel to retrieve messages from.
- Returns:
JSON string containing filtered message data.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel message.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- join_slack_channel(channel_id: str) str [source]#
Joins an existing Slack channel.
- Parameters:
channel_id (str) – The ID of the Slack channel to join.
- Returns:
- A confirmation message indicating whether join successfully
or an error message.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel information.
- leave_slack_channel(channel_id: str) str [source]#
Leaves an existing Slack channel.
- Parameters:
channel_id (str) – The ID of the Slack channel to leave.
- Returns:
- A confirmation message indicating whether leave successfully
or an error message.
- Return type:
str
- Raises:
SlackApiError – If there is an error during get slack channel information.
- send_slack_message(message: str, channel_id: str, user: str | None = None) str [source]#
Send a message to a Slack channel.
- Parameters:
message (str) – The message to send.
channel_id (str) – The ID of the Slack channel to send message.
user (Optional[str]) – The user ID of the recipient. Defaults to None.
- Returns:
- A confirmation message indicating whether the message was sent
successfully or an error message.
- Return type:
str
- Raises:
SlackApiError – If an error occurs while sending the message.
- class camel.toolkits.StripeToolkit(retries: int = 3)[source]#
Bases:
BaseToolkit
A class representing a toolkit for Stripe operations.
This toolkit provides methods to interact with the Stripe API, allowing users to operate stripe core resources, including Customer, Balance, BalanceTransaction, Payment, Refund
Use the Developers Dashboard https://dashboard.stripe.com/test/apikeys to create an API keys as STRIPE_API_KEY.
- logger#
a logger to write logs.
- Type:
Logger
- balance_get() str [source]#
Retrieve your account balance.
- Returns:
- A str containing the account balance if successful, or an
error message string if failed.
- Return type:
str
- balance_transaction_list(limit: int = 100) str [source]#
List your balance transactions.
- Parameters:
limit (int, optional) – Number of balance transactions to retrieve. (default:
100
)- Returns:
- A list of balance transaction data if successful, or an error
message string if failed.
- Return type:
str
- customer_get(customer_id: str) str [source]#
Retrieve a customer by ID.
- Parameters:
customer_id (str) – The ID of the customer to retrieve.
- Returns:
The customer data as a str.
- Return type:
str
- customer_list(limit: int = 100) str [source]#
List customers.
- Parameters:
limit (int, optional) – Number of customers to retrieve. (default:
100
)- Returns:
- An output str if successful, or an error message string if
failed.
- Return type:
str
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects for the
toolkit methods.
- Return type:
List[FunctionTool]
- handle_exception(func_name: str, error: Exception) str [source]#
Handle exceptions by logging and returning an error message.
- Parameters:
func_name (str) – The name of the function where the exception occurred.
error (Exception) – The exception instance.
- Returns:
An error message string.
- Return type:
str
- payment_get(payment_id: str) str [source]#
Retrieve a payment by ID.
- Parameters:
payment_id (str) – The ID of the payment to retrieve.
- Returns:
- The payment data as a str if successful, or an error message
string if failed.
- Return type:
str
- payment_list(limit: int = 100) str [source]#
List payments.
- Parameters:
limit (int, optional) – Number of payments to retrieve. (default:
100
)- Returns:
- A list of payment data if successful, or an error message
string if failed.
- Return type:
str
- class camel.toolkits.TwitterToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for Twitter operations.
This class provides methods for creating a tweet, deleting a tweet, and getting the authenticated user’s profile information.
References
https://developer.x.com/en/portal/dashboard
Notes
To use this toolkit, you need to set the following environment variables: - TWITTER_CONSUMER_KEY: The consumer key for the Twitter API. - TWITTER_CONSUMER_SECRET: The consumer secret for the Twitter API. - TWITTER_ACCESS_TOKEN: The access token for the Twitter API. - TWITTER_ACCESS_TOKEN_SECRET: The access token secret for the Twitter
API.
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- class camel.toolkits.VideoDownloaderToolkit(download_directory: str | None = None, cookies_path: str | None = None)[source]#
Bases:
BaseToolkit
A class for downloading videos and optionally splitting them into chunks.
- Parameters:
download_directory (Optional[str], optional) – The directory where the video will be downloaded to. If not provided, video will be stored in a temporary directory and will be cleaned up after use. (default:
None
)cookies_path (Optional[str], optional) – The path to the cookies file for the video service in Netscape format. (default:
None
)
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects representing
the functions in the toolkit.
- Return type:
List[FunctionTool]
- get_video_bytes(video_url: str) bytes [source]#
Download video by the URL, and return the content in bytes.
- Parameters:
video_url (str) – The URL of the video to download.
- Returns:
The video file content in bytes.
- Return type:
bytes
- get_video_screenshots(video_url: str, amount: int) List[Image] [source]#
Capture screenshots from the video at specified timestamps or by dividing the video into equal parts if an integer is provided.
- Parameters:
video_url (str) – The URL of the video to take screenshots.
amount (int) – the amount of evenly split screenshots to capture.
- Returns:
A list of screenshots as Image.Image.
- Return type:
List[Image.Image]
- class camel.toolkits.WeatherToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for interacting with weather data.
This class provides methods for fetching weather data for a given city using the OpenWeatherMap API.
- get_openweathermap_api_key() str [source]#
Retrieve the OpenWeatherMap API key from environment variables.
- Returns:
The OpenWeatherMap API key.
- Return type:
str
- Raises:
ValueError – If the API key is not found in the environment
variables. –
- get_tools() List[FunctionTool] [source]#
Returns a list of FunctionTool objects representing the functions in the toolkit.
- Returns:
- A list of FunctionTool objects
representing the functions in the toolkit.
- Return type:
List[FunctionTool]
- get_weather_data(city: str, temp_units: Literal['kelvin', 'celsius', 'fahrenheit'] = 'kelvin', wind_units: Literal['meters_sec', 'miles_hour', 'knots', 'beaufort'] = 'meters_sec', visibility_units: Literal['meters', 'miles'] = 'meters', time_units: Literal['unix', 'iso', 'date'] = 'unix') str [source]#
Fetch and return a comprehensive weather report for a given city as a string. The report includes current weather conditions, temperature, wind details, visibility, and sunrise/sunset times, all formatted as a readable string.
The function interacts with the OpenWeatherMap API to retrieve the data.
- Parameters:
city (str) – The name of the city for which the weather information is desired. Format “City, CountryCode” (e.g., “Paris, FR” for Paris, France). If the country code is not provided, the API will search for the city in all countries, which may yield incorrect results if multiple cities with the same name exist.
temp_units (Literal['kelvin', 'celsius', 'fahrenheit']) – Units for temperature. (default:
kelvin
)wind_units – (Literal[‘meters_sec’, ‘miles_hour’, ‘knots’, ‘beaufort’]): Units for wind speed. (default:
meters_sec
)visibility_units (Literal['meters', 'miles']) – Units for visibility distance. (default:
meters
)time_units (Literal['unix', 'iso', 'date']) – Format for sunrise and sunset times. (default:
unix
)
- Returns:
- A string containing the fetched weather data, formatted in a
readable manner. If an error occurs, a message indicating the error will be returned instead.
- Return type:
str
- Example of return string:
“Weather in Paris, FR: 15°C, feels like 13°C. Max temp: 17°C, Min temp : 12°C. Wind: 5 m/s at 270 degrees. Visibility: 10 kilometers. Sunrise at 05:46:05 (UTC), Sunset at 18:42:20 (UTC).”
Note
- Please ensure that the API key is valid and has permissions
to access the weather data.
- camel.toolkits.generate_docstring(code: str, model: BaseModelBackend | None = None) str [source]#
Generates a docstring for a given function code using LLM.
This function leverages a language model to generate a PEP 8/PEP 257-compliant docstring for a provided Python function. If no model is supplied, a default gpt-4o-mini is used.
- Parameters:
code (str) – The source code of the function.
model (Optional[BaseModelBackend]) – An optional language model backend instance. If not provided, a default gpt-4o-mini is used.
- Returns:
The generated docstring.
- Return type:
str
- camel.toolkits.get_openai_function_schema(func: Callable) Dict[str, Any] [source]#
Generates a schema dict for an OpenAI function based on its signature.
This function is deprecated and will be replaced by
get_openai_tool_schema()
in future versions. It parses the function’s parameters and docstring to construct a JSON schema-like dictionary.- Parameters:
func (Callable) – The OpenAI function to generate the schema for.
- Returns:
- A dictionary representing the JSON schema of the
function, including its name, description, and parameter specifications.
- Return type:
Dict[str, Any]
- camel.toolkits.get_openai_tool_schema(func: Callable) Dict[str, Any] [source]#
Generates an OpenAI JSON schema from a given Python function.
This function creates a schema compatible with OpenAI’s API specifications, based on the provided Python function. It processes the function’s parameters, types, and docstrings, and constructs a schema accordingly.
Note
Each parameter in func must have a type annotation; otherwise, it’s treated as ‘Any’.
Variable arguments (*args) and keyword arguments (**kwargs) are not supported and will be ignored.
A functional description including a brief and detailed explanation should be provided in the docstring of func.
All parameters of func must be described in its docstring.
Supported docstring styles: ReST, Google, Numpydoc, and Epydoc.
- Parameters:
func (Callable) – The Python function to be converted into an OpenAI JSON schema.
- Returns:
- A dictionary representing the OpenAI JSON schema of
the provided function.
- Return type:
Dict[str, Any]
See also
- `OpenAI API Reference
<https://platform.openai.com/docs/api-reference/assistants/object>`_