camel.toolkits package#
Submodules#
camel.toolkits.base module#
- class camel.toolkits.base.BaseToolkit[source]#
Bases:
object
- get_tools() List[OpenAIFunction] [source]#
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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
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.
This class provides methods handle image generation using OpenAI’s DALL-E.
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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.GithubIssue(*, title: str, body: str, number: int, file_path: str, file_content: str)[source]#
Bases:
BaseModel
Represents a GitHub issue.
- title#
The title of the issue.
- Type:
str
- body#
The body/content of the issue.
- Type:
str
- number#
The issue number.
- Type:
int
- file_path#
The path of the file associated with the issue.
- Type:
str
- file_content#
The content of the file associated with the issue.
- Type:
str
- body: str#
- file_content: str#
- file_path: str#
- model_computed_fields: ClassVar[Dict[str, ComputedFieldInfo]] = {}#
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[Dict[str, FieldInfo]] = {'body': FieldInfo(annotation=str, required=True), 'file_content': FieldInfo(annotation=str, required=True), 'file_path': FieldInfo(annotation=str, required=True), 'number': FieldInfo(annotation=int, required=True), 'title': FieldInfo(annotation=str, required=True)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo] objects.
This replaces Model.__fields__ from Pydantic V1.
- number: int#
- title: str#
- class camel.toolkits.github_toolkit.GithubPullRequest(*, title: str, body: str, diffs: List[GithubPullRequestDiff])[source]#
Bases:
BaseModel
Represents a pull request on Github.
- title#
The title of the GitHub pull request.
- Type:
str
- body#
The body/content of the GitHub pull request.
- Type:
str
- diffs#
A list of diffs for the pull request.
- Type:
List[GithubPullRequestDiff]
- body: str#
- diffs: List[GithubPullRequestDiff]#
- model_computed_fields: ClassVar[Dict[str, ComputedFieldInfo]] = {}#
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[Dict[str, FieldInfo]] = {'body': FieldInfo(annotation=str, required=True), 'diffs': FieldInfo(annotation=List[GithubPullRequestDiff], required=True), 'title': FieldInfo(annotation=str, required=True)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo] objects.
This replaces Model.__fields__ from Pydantic V1.
- title: str#
- class camel.toolkits.github_toolkit.GithubPullRequestDiff(*, filename: str, patch: str)[source]#
Bases:
BaseModel
Represents a single diff of a pull request on Github.
- filename#
The name of the file that was changed.
- Type:
str
- patch#
The diff patch for the file.
- Type:
str
- filename: str#
- model_computed_fields: ClassVar[Dict[str, ComputedFieldInfo]] = {}#
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[Dict[str, FieldInfo]] = {'filename': FieldInfo(annotation=str, required=True), 'patch': FieldInfo(annotation=str, required=True)}#
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo] objects.
This replaces Model.__fields__ from Pydantic V1.
- patch: str#
- 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_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_tools() List[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- retrieve_file_content(file_path: str) str [source]#
Retrieves the content of a file from the GitHub repository.
- Parameters:
file_path (str) – The path of the file to retrieve.
- Returns:
The decoded content of the file.
- Return type:
str
- retrieve_issue(issue_number: int) str | None [source]#
Retrieves an issue from a GitHub repository.
This function retrieves an issue from a specified repository using the issue number.
- Parameters:
issue_number (int) – The number of the issue to retrieve.
- Returns:
A formatted report of the retrieved issue.
- Return type:
str
- retrieve_issue_list() List[GithubIssue] [source]#
Retrieve a list of open issues from the repository.
- Returns:
A list of GithubIssue objects representing the open issues.
- retrieve_pull_requests(days: int, state: str, max_prs: int) List[str] [source]#
Retrieves a summary of merged pull requests from the repository. The summary will be provided for the last specified number of days.
- Parameters:
days (int) – The number of days to retrieve merged pull requests for.
state (str) – A specific state of PRs to retrieve. Can be open or closed.
max_prs (int) – The maximum number of PRs to retrieve.
- Returns:
A list of merged pull request summaries.
- Return type:
List[str]
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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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.openai_function.OpenAIFunction(func: Callable, openai_tool_schema: Dict[str, Any] | 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 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
)
- 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.
- 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.
ValueError – If the function description or parameter descriptions are missing in the schema.
SchemaError – If the parameters do not meet JSON Schema reference specifications.
- camel.toolkits.openai_function.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.openai_function.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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects for the
toolkit methods.
- Return type:
List[OpenAIFunction]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- query_wolfram_alpha(query: str, is_detailed: bool) str [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 in the result.
- Returns:
The result from Wolfram Alpha, formatted as a string.
- Return type:
str
- 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
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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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.
- 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.
Note
You can only provide either the quote_tweet_id parameter or the pair of poll_duration_minutes and poll_options parameters, not both.
- 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
- Reference:
https://developer.twitter.com/en/docs/twitter-api/tweets/ manage-tweets/api-reference/post-tweets xdevplatform/Twitter-API-v2-sample-code main/Manage-Tweets/create_tweet.py
- 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
- Reference:
https://developer.twitter.com/en/docs/twitter-api/tweets/ manage-tweets/api-reference/delete-tweets-id
- get_my_user_profile() str [source]#
Retrieves and formats 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
- Reference:
https://developer.twitter.com/en/docs/twitter-api/users/lookup/ api-reference/get-users-me
- get_tools() List[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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.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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- class camel.toolkits.DalleToolkit[source]#
Bases:
BaseToolkit
A class representing a toolkit for image generation using OpenAI’s.
This class provides methods handle image generation using OpenAI’s DALL-E.
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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.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_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_tools() List[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- retrieve_file_content(file_path: str) str [source]#
Retrieves the content of a file from the GitHub repository.
- Parameters:
file_path (str) – The path of the file to retrieve.
- Returns:
The decoded content of the file.
- Return type:
str
- retrieve_issue(issue_number: int) str | None [source]#
Retrieves an issue from a GitHub repository.
This function retrieves an issue from a specified repository using the issue number.
- Parameters:
issue_number (int) – The number of the issue to retrieve.
- Returns:
A formatted report of the retrieved issue.
- Return type:
str
- retrieve_issue_list() List[GithubIssue] [source]#
Retrieve a list of open issues from the repository.
- Returns:
A list of GithubIssue objects representing the open issues.
- retrieve_pull_requests(days: int, state: str, max_prs: int) List[str] [source]#
Retrieves a summary of merged pull requests from the repository. The summary will be provided for the last specified number of days.
- Parameters:
days (int) – The number of days to retrieve merged pull requests for.
state (str) – A specific state of PRs to retrieve. Can be open or closed.
max_prs (int) – The maximum number of PRs to retrieve.
- Returns:
A list of merged pull request summaries.
- Return type:
List[str]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- class camel.toolkits.OpenAIFunction(func: Callable, openai_tool_schema: Dict[str, Any] | 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 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
)
- 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.
- 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.
ValueError – If the function description or parameter descriptions are missing in the schema.
SchemaError – If the parameters do not meet JSON Schema reference specifications.
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects for the
toolkit methods.
- Return type:
List[OpenAIFunction]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- query_wolfram_alpha(query: str, is_detailed: bool) str [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 in the result.
- Returns:
The result from Wolfram Alpha, formatted as a string.
- Return type:
str
- 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
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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.
- 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.
Note
You can only provide either the quote_tweet_id parameter or the pair of poll_duration_minutes and poll_options parameters, not both.
- 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
- Reference:
https://developer.twitter.com/en/docs/twitter-api/tweets/ manage-tweets/api-reference/post-tweets xdevplatform/Twitter-API-v2-sample-code main/Manage-Tweets/create_tweet.py
- 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
- Reference:
https://developer.twitter.com/en/docs/twitter-api/tweets/ manage-tweets/api-reference/delete-tweets-id
- get_my_user_profile() str [source]#
Retrieves and formats 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
- Reference:
https://developer.twitter.com/en/docs/twitter-api/users/lookup/ api-reference/get-users-me
- get_tools() List[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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[OpenAIFunction] [source]#
Returns a list of OpenAIFunction objects representing the functions in the toolkit.
- Returns:
- A list of OpenAIFunction objects
representing the functions in the toolkit.
- Return type:
List[OpenAIFunction]
- 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.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>`_