tooluniverse.output_hook module

Output Hook System for ToolUniverse

This module provides a comprehensive hook-based output processing system that allows for intelligent post-processing of tool outputs. The system supports various types of hooks including summarization, filtering, and transformation hooks.

Key Components: - HookRule: Defines conditions for when hooks should trigger - OutputHook: Base class for all output hooks - SummarizationHook: Specialized hook for output summarization - HookManager: Manages and coordinates all hooks

The hook system integrates seamlessly with ToolUniverse’s existing architecture, leveraging AgenticTool and ComposeTool for intelligent output processing.

class tooluniverse.output_hook.Path(*args, **kwargs)[source][source]

Bases: PurePath

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

classmethod cwd()[source][source]

Return a new path pointing to the current working directory (as returned by os.getcwd()).

classmethod home()[source][source]

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

samefile(other_path)[source][source]

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

iterdir()[source][source]

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

glob(pattern)[source][source]

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

rglob(pattern)[source][source]

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

absolute()[source][source]

Return an absolute version of this path. This function works even if the path doesn’t point to anything.

No normalization is done, i.e. all ‘.’ and ‘..’ will be kept along. Use resolve() to get the canonical path to a file.

resolve(strict=False)[source][source]

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).

stat(*, follow_symlinks=True)[source][source]

Return the result of the stat() system call on this path, like os.stat() does.

owner()[source][source]

Return the login name of the file owner.

group()[source][source]

Return the group name of the file gid.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)[source][source]

Open the file pointed by this path and return a file object, as the built-in open() function does.

read_bytes()[source][source]

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)[source][source]

Open the file in text mode, read it, and close the file.

write_bytes(data)[source][source]

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)[source][source]

Open the file in text mode, write to it, and close the file.

Return the path to which the symbolic link points.

touch(mode=438, exist_ok=True)[source][source]

Create this file with the given access mode, if it doesn’t exist.

mkdir(mode=511, parents=False, exist_ok=False)[source][source]

Create a new directory at this given path.

chmod(mode, *, follow_symlinks=True)[source][source]

Change the permissions of the path, like os.chmod().

lchmod(mode)[source][source]

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

Remove this file or link. If the path is a directory, use rmdir() instead.

rmdir()[source][source]

Remove this directory. The directory must be empty.

lstat()[source][source]

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

rename(target)[source][source]

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)[source][source]

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

Make the target path a hard link pointing to this path.

Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.

Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.

exists()[source][source]

Whether this path exists.

is_dir()[source][source]

Whether this path is a directory.

is_file()[source][source]

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()[source][source]

Check if this path is a POSIX mount point

Whether this path is a symbolic link.

is_block_device()[source][source]

Whether this path is a block device.

is_char_device()[source][source]

Whether this path is a character device.

is_fifo()[source][source]

Whether this path is a FIFO.

is_socket()[source][source]

Whether this path is a socket.

expanduser()[source][source]

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

class tooluniverse.output_hook.HookRule(conditions: Dict[str, Any])[source][source]

Bases: object

Defines rules for when hooks should be triggered.

This class evaluates various conditions to determine if a hook should be applied to a tool’s output. Supports multiple condition types including output length, content type, and tool-specific criteria.

Parameters:

conditions (Dict[str, Any]) – Dictionary containing condition specifications

conditions[source]

The condition specifications

Type:

Dict[str, Any]

__init__(conditions: Dict[str, Any])[source][source]

Initialize the hook rule with conditions.

Parameters:

conditions (Dict[str, Any]) – Condition specifications including output_length, content_type, tool_type, etc.

evaluate(result: Any, tool_name: str, arguments: Dict[str, Any], context: Dict[str, Any]) bool[source][source]

Evaluate whether the rule conditions are met.

Parameters:
  • result (Any) – The tool output to evaluate

  • tool_name (str) – Name of the tool that produced the output

  • arguments (Dict[str, Any]) – Arguments passed to the tool

  • context (Dict[str, Any]) – Additional context information

Returns:

True if conditions are met, False otherwise

Return type:

bool

class tooluniverse.output_hook.OutputHook(config: Dict[str, Any])[source][source]

Bases: object

Base class for all output hooks.

This abstract base class defines the interface that all output hooks must implement. Hooks are used to process tool outputs after execution, enabling features like summarization, filtering, transformation, and validation.

Parameters:

config (Dict[str, Any]) – Hook configuration including name, enabled status, priority, and conditions

config[source]

Hook configuration

Type:

Dict[str, Any]

name[source]

Name of the hook

Type:

str

enabled[source]

Whether the hook is enabled

Type:

bool

priority[source]

Hook priority (lower numbers execute first)

Type:

int

rule[source]

Rule for when this hook should trigger

Type:

HookRule

__init__(config: Dict[str, Any])[source][source]

Initialize the output hook with configuration.

Parameters:

config (Dict[str, Any]) – Hook configuration containing: - name: Hook identifier - enabled: Whether hook is active - priority: Execution priority - conditions: Trigger conditions

should_trigger(result: Any, tool_name: str, arguments: Dict[str, Any], context: Dict[str, Any]) bool[source][source]

Determine if this hook should be triggered for the given output.

Parameters:
  • result (Any) – The tool output to evaluate

  • tool_name (str) – Name of the tool that produced the output

  • arguments (Dict[str, Any]) – Arguments passed to the tool

  • context (Dict[str, Any]) – Additional context information

Returns:

True if hook should trigger, False otherwise

Return type:

bool

process(result: Any, tool_name: str, arguments: Dict[str, Any], context: Dict[str, Any]) Any[source][source]

Process the tool output.

This method must be implemented by subclasses to define the specific processing logic for the hook.

Parameters:
  • result (Any) – The tool output to process

  • tool_name (str) – Name of the tool that produced the output

  • arguments (Dict[str, Any]) – Arguments passed to the tool

  • context (Dict[str, Any]) – Additional context information

Returns:

The processed output

Return type:

Any

Raises:

NotImplementedError – If not implemented by subclass

class tooluniverse.output_hook.SummarizationHook(config: Dict[str, Any], tooluniverse)[source][source]

Bases: OutputHook

Hook for intelligent output summarization using AI.

This hook uses the ToolUniverse’s AgenticTool and ComposeTool infrastructure to provide intelligent summarization of long tool outputs. It supports chunking large outputs, processing each chunk with AI, and merging results.

Parameters:
  • config (Dict[str, Any]) – Hook configuration including summarization parameters

  • tooluniverse – Reference to the ToolUniverse instance

tooluniverse[source]

ToolUniverse instance for tool execution

composer_tool_name[source]

Name of the ComposeTool for summarization

Type:

str

chunk_size[source]

Size of chunks for processing large outputs

Type:

int

focus_areas[source]

Areas to focus on during summarization

Type:

str

max_summary_length[source]

Maximum length of final summary

Type:

int

__init__(config: Dict[str, Any], tooluniverse)[source][source]

Initialize the summarization hook.

Parameters:
  • config (Dict[str, Any]) – Hook configuration

  • tooluniverse – ToolUniverse instance for executing summarization tools

process(result: Any, tool_name: str, arguments: Dict[str, Any], context: Dict[str, Any]) Any[source][source]

Execute summarization processing using Compose Summarizer Tool.

This method orchestrates the summarization workflow by: 1. Preparing parameters for the Compose Summarizer Tool 2. Calling the tool through ToolUniverse 3. Processing and returning the summarized result

Parameters:
  • result (Any) – The tool output to summarize

  • tool_name (str) – Name of the tool that produced the output

  • arguments (Dict[str, Any]) – Arguments passed to the tool

  • context (Dict[str, Any]) – Additional context information

Returns:

The summarized output, or original output if summarization fails

Return type:

Any

class tooluniverse.output_hook.HookManager(config: Dict[str, Any], tooluniverse)[source][source]

Bases: object

Manages and coordinates all output hooks.

The HookManager is responsible for loading hook configurations, creating hook instances, and applying hooks to tool outputs. It provides a unified interface for hook management and supports dynamic configuration updates.

Parameters:
  • config (Dict[str, Any]) – Hook manager configuration

  • tooluniverse – Reference to the ToolUniverse instance

config[source]

Hook manager configuration

Type:

Dict[str, Any]

tooluniverse[source]

ToolUniverse instance for tool execution

hooks[source]

List of loaded hook instances

Type:

List[OutputHook]

enabled[source]

Whether hook processing is enabled

Type:

bool

config_path[source]

Path to hook configuration file

Type:

str

__init__(config: Dict[str, Any], tooluniverse)[source][source]

Initialize the hook manager.

Parameters:
  • config (Dict[str, Any]) – Configuration for hook manager

  • tooluniverse – ToolUniverse instance for executing tools

apply_hooks(result: Any, tool_name: str, arguments: Dict[str, Any], context: Dict[str, Any]) Any[source][source]

Apply all applicable hooks to the tool output.

This method iterates through all loaded hooks, checks if they should be applied to the current output, and processes the output through each applicable hook in priority order.

Parameters:
  • result (Any) – The tool output to process

  • tool_name (str) – Name of the tool that produced the output

  • arguments (Dict[str, Any]) – Arguments passed to the tool

  • context (Dict[str, Any]) – Additional context information

Returns:

The processed output after applying all applicable hooks

Return type:

Any

enable_hook(hook_name: str)[source][source]

Enable a specific hook by name.

Parameters:

hook_name (str) – Name of the hook to enable

disable_hook(hook_name: str)[source][source]

Disable a specific hook by name.

Parameters:

hook_name (str) – Name of the hook to disable

toggle_hooks(enabled: bool)[source][source]

Enable or disable all hooks globally.

Parameters:

enabled (bool) – True to enable all hooks, False to disable

reload_config(config_path: str | None = None)[source][source]

Reload hook configuration from file.

Parameters:

config_path (Optional[str]) – Path to configuration file. If None, uses the current config_path

get_hook(hook_name: str) OutputHook | None[source][source]

Get a hook instance by name.

Parameters:

hook_name (str) – Name of the hook to retrieve

Returns:

Hook instance if found, None otherwise

Return type:

Optional[OutputHook]

class tooluniverse.output_hook.FileSaveHook(config: Dict[str, Any])[source][source]

Bases: OutputHook

Hook that saves tool outputs to temporary files and returns file information.

This hook saves the tool output to a temporary file and returns information about the file path, data format, and data structure instead of the original output. This is useful for handling large outputs or when you need to process outputs as files rather than in-memory data.

Configuration options: - temp_dir: Directory to save temporary files (default: system temp) - file_prefix: Prefix for generated filenames (default: ‘tool_output’) - include_metadata: Whether to include metadata in the response (default: True) - auto_cleanup: Whether to automatically clean up old files (default: False) - cleanup_age_hours: Age in hours for auto cleanup (default: 24)

__init__(config: Dict[str, Any])[source][source]

Initialize the FileSaveHook.

Parameters:

config (Dict[str, Any]) – Hook configuration including: - name: Hook name - temp_dir: Directory for temporary files - file_prefix: Prefix for filenames - include_metadata: Include metadata flag - auto_cleanup: Auto cleanup flag - cleanup_age_hours: Cleanup age in hours

process(result: Any, tool_name: str, arguments: Dict[str, Any], context: Dict[str, Any]) Dict[str, Any][source][source]

Process the tool output by saving it to a temporary file.

Parameters:
  • result (Any) – The tool output to process

  • tool_name (str) – Name of the tool that produced the output

  • arguments (Dict[str, Any]) – Arguments passed to the tool

  • context (Dict[str, Any]) – Execution context

Returns:

Dictionary containing file information:
  • file_path: Path to the saved file

  • data_format: Format of the data (json, text, binary, etc.)

  • data_structure: Structure information about the data

  • file_size: Size of the file in bytes

  • created_at: Timestamp when file was created

  • metadata: Additional metadata (if include_metadata is True)

Return type:

Dict[str, Any]