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'] = 'internal_python', verbose: bool = False)[source]#
Bases:
BaseToolkit
A tookit for code execution.
- Parameters:
sandbox (str) – the environment type used to execute code.
- 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, and multiplication.
- add(a: int, b: int) int [source]#
Adds two numbers.
- Parameters:
a (int) – The first number to be added.
b (int) – The second number to be added.
- Returns:
The sum of the two numbers.
- Return type:
integer
- 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.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.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.
- 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_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_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'] = 'internal_python', verbose: bool = False)[source]#
Bases:
BaseToolkit
A tookit for code execution.
- Parameters:
sandbox (str) – the environment type used to execute code.
- 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.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)[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.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, and multiplication.
- add(a: int, b: int) int [source]#
Adds two numbers.
- Parameters:
a (int) – The first number to be added.
b (int) – The second number to be added.
- Returns:
The sum of the two numbers.
- Return type:
integer
- 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.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.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.
- 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_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_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.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.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>`_