-
Notifications
You must be signed in to change notification settings - Fork 24
Use importlib.resources to resolve tool name to a file location #37
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
kevinbackhouse
merged 6 commits into
GitHubSecurityLab:main
from
kevinbackhouse:importlib
Oct 27, 2025
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5f9c969
Use importlib.resources to resolve tool name to a file location.
kevinbackhouse f890429
Fix test
kevinbackhouse c294e37
Remove unused imports
kevinbackhouse 7fc075f
Update available_tools.py
kevinbackhouse 5221e25
Remove unused import
kevinbackhouse 09e05de
Add error check.
kevinbackhouse File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,64 +1,88 @@ | ||
| from enum import Enum | ||
| import logging | ||
| import importlib.resources | ||
| import yaml | ||
|
|
||
| class VersionException(Exception): | ||
| class BadToolNameError(Exception): | ||
| pass | ||
|
|
||
| class FileIDException(Exception): | ||
| class VersionException(Exception): | ||
| pass | ||
|
|
||
| class FileTypeException(Exception): | ||
| pass | ||
|
|
||
| def add_yaml_to_dict(table, key, yaml): | ||
| """Add the yaml to the table, but raise an error if the id isn't unique """ | ||
| if key in table: | ||
| raise FileIDException(str(key)) | ||
| table.update({key: yaml}) | ||
| class AvailableToolType(Enum): | ||
| Personality = "personality" | ||
| Taskflow = "taskflow" | ||
| Prompt = "prompt" | ||
| Toolbox = "toolbox" | ||
| ModelConfig = "model_config" | ||
|
|
||
| class AvailableTools: | ||
| """ | ||
| This class is used for storing dictionaries of all the available | ||
| personalities, taskflows, and prompts. | ||
| """ | ||
| def __init__(self, yamls: dict): | ||
| self.personalities = {} | ||
| self.taskflows = {} | ||
| self.prompts = {} | ||
| self.toolboxes = {} | ||
| self.model_config = {} | ||
| def __init__(self): | ||
| self.__yamlcache = {} | ||
|
|
||
| def get_personality(self, name: str): | ||
| return self.get_tool(AvailableToolType.Personality, name) | ||
|
|
||
| def get_taskflow(self, name: str): | ||
| return self.get_tool(AvailableToolType.Taskflow, name) | ||
|
|
||
| def get_prompt(self, name: str): | ||
| return self.get_tool(AvailableToolType.Prompt, name) | ||
|
|
||
| def get_toolbox(self, name: str): | ||
| return self.get_tool(AvailableToolType.Toolbox, name) | ||
|
|
||
| def get_model_config(self, name: str): | ||
| return self.get_tool(AvailableToolType.ModelConfig, name) | ||
|
|
||
| # Iterate through all the yaml files and divide them into categories. | ||
| # Each file should contain a header like this: | ||
| # | ||
| # seclab-taskflow-agent: | ||
| # type: taskflow | ||
| # version: 1 | ||
| # | ||
| for path, yaml in yamls.items(): | ||
| try: | ||
| header = yaml['seclab-taskflow-agent'] | ||
| def get_tool(self, tooltype: AvailableToolType, toolname: str): | ||
| """for example: available_tools.get_tool("personality", "personalities/fruit_expert") | ||
| This method first checks whether the tool has already been loaded. If not, it | ||
| finds the yaml file and parses it. It also checks that the filetype in the header | ||
| matches the expected tooltype. | ||
| """ | ||
| try: | ||
| return self.__yamlcache[tooltype][toolname] | ||
| except KeyError: | ||
| pass | ||
| # Split the string to get the path and filename. | ||
| components = toolname.rsplit('.', 1) | ||
| if len(components) == 2: | ||
| path = components[0] | ||
| filename = components[1] | ||
| else: | ||
| path = '' | ||
| filename = toolname | ||
| try: | ||
| d = importlib.resources.files(path) | ||
| if not d.is_dir(): | ||
| raise BadToolNameError(f'Cannot load {toolname} because {d} is not a valid directory.') | ||
| f = d.joinpath(filename + ".yaml") | ||
| with open(f) as s: | ||
| y = yaml.safe_load(s) | ||
| header = y['seclab-taskflow-agent'] | ||
| version = header['version'] | ||
| if version != 1: | ||
| raise VersionException(str(version)) | ||
| filekey = header['filekey'] | ||
| filetype = header['filetype'] | ||
| if filetype == 'personality': | ||
| add_yaml_to_dict(self.personalities, filekey, yaml) | ||
| elif filetype == 'taskflow': | ||
| add_yaml_to_dict(self.taskflows, filekey, yaml) | ||
| elif filetype == 'prompt': | ||
| add_yaml_to_dict(self.prompts, filekey, yaml) | ||
| elif filetype == 'toolbox': | ||
| add_yaml_to_dict(self.toolboxes, filekey, yaml) | ||
| elif filetype == 'model_config': | ||
| add_yaml_to_dict(self.model_config, filekey, yaml) | ||
| else: | ||
| raise FileTypeException(str(filetype)) | ||
| except KeyError as err: | ||
| logging.error(f'{path} does not contain the key {err.args[0]}') | ||
| except VersionException as err: | ||
| logging.error(f'{path}: seclab-taskflow-agent version {err.args[0]} is not supported') | ||
| except FileIDException as err: | ||
| logging.error(f'{path}: file ID {err.args[0]} is not unique') | ||
| except FileTypeException as err: | ||
| logging.error(f'{path}: seclab-taskflow-agent file type {err.args[0]} is not supported') | ||
| filetype = header['filetype'] | ||
| if filetype != tooltype.value: | ||
| raise FileTypeException( | ||
| f'Error in {f}: expected filetype to be {tooltype}, but it\'s {filetype}.') | ||
| if not tooltype in self.__yamlcache: | ||
| self.__yamlcache[tooltype] = {} | ||
| self.__yamlcache[tooltype][toolname] = y | ||
| return y | ||
| except ModuleNotFoundError as e: | ||
| raise BadToolNameError(f'Cannot load {toolname}: {e}') | ||
| except FileNotFoundError: | ||
| # deal with editor temp files etc. that might have disappeared | ||
| raise BadToolNameError(f'Cannot load {toolname} because {f} is not a valid file.') | ||
| except ValueError as e: | ||
| raise BadToolNameError(f'Cannot load {toolname}: {e}') | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.