Tools API

This section documents the available tools in AIECS.

Tool Configuration

Tool Config Loader

Configuration loader for tool configurations.

This module provides a singleton configuration loader that loads and manages tool configurations from YAML files and .env files with support for sensitive credential separation and runtime configuration management.

class aiecs.config.tool_config.ToolConfigLoader[source]

Bases: object

Singleton configuration loader for tools.

Supports: - Loading sensitive configuration from .env files (via dotenv) - Loading runtime configuration from YAML files - Configuration merging with precedence order - Schema validation against tool’s Pydantic Config class - Config directory discovery (walking up directory tree) - Thread-safe access - Caching for performance

static __new__(cls)[source]

Ensure singleton instance

__init__()[source]

Initialize the configuration loader

Return type:

None

find_config_directory()[source]

Discover config/ directory in project.

Search order: 1. Custom config path set via set_config_path() 2. Settings tool_config_path (if available) 3. Environment variable TOOL_CONFIG_PATH 4. Walk up directory tree from current working directory 5. Check aiecs/config/ directory

Returns:

Path to config directory if found, None otherwise

Return type:

Path | None

load_env_config()[source]

Load sensitive configuration from .env files via dotenv.

Supports multiple .env files in order: 1. .env (base) 2. .env.local (local overrides) 3. .env.production (production overrides, if NODE_ENV=production)

Returns:

Dictionary of environment variables loaded from .env files

Return type:

Dict[str, Any]

load_yaml_config(tool_name)[source]

Load runtime configuration from YAML files.

Loads from: 1. Tool-specific: config/tools/{tool_name}.yaml 2. Global: config/tools.yaml

Tool-specific config takes precedence over global config.

Parameters:

tool_name (str) – Name of the tool (e.g., “DocumentParserTool”)

Returns:

Dictionary of configuration values from YAML files

Return type:

Dict[str, Any]

merge_config(explicit_config=None, yaml_config=None, env_config=None, defaults=None)[source]

Merge configurations according to precedence order.

Precedence (highest to lowest): 1. Explicit config dict 2. YAML config 3. Environment variables 4. Defaults

Parameters:
  • explicit_config (Dict[str, Any] | None) – Explicit configuration dict (highest priority)

  • yaml_config (Dict[str, Any] | None) – Configuration from YAML files

  • env_config (Dict[str, Any] | None) – Configuration from environment variables

  • defaults (Dict[str, Any] | None) – Default configuration values (lowest priority)

Returns:

Merged configuration dictionary

Return type:

Dict[str, Any]

validate_config(config_dict, config_schema)[source]

Validate merged config against tool’s Pydantic schema.

Parameters:
  • config_dict (Dict[str, Any]) – Configuration dictionary to validate

  • config_schema (Type[BaseModel]) – Pydantic model class for validation

Returns:

Validated configuration dictionary

Raises:

ValidationError – If configuration is invalid

Return type:

Dict[str, Any]

load_tool_config(tool_name, config_schema=None, explicit_config=None)[source]

Main entry point for loading tool configuration.

Loads, merges, and validates configuration from all sources: 1. Explicit config dict (highest priority) 2. YAML config files (tool-specific and global) 3. Environment variables (via dotenv) 4. Tool defaults (lowest priority)

Parameters:
  • tool_name (str) – Name of the tool (e.g., “DocumentParserTool”)

  • config_schema (Type[BaseModel] | None) – Optional Pydantic model class for validation

  • explicit_config (Dict[str, Any] | None) – Optional explicit configuration dict (overrides everything)

Returns:

Merged and validated configuration dictionary

Raises:

ValidationError – If config_schema is provided and validation fails

Return type:

Dict[str, Any]

set_config_path(path=None)[source]

Set custom config path.

Parameters:

path (str | Path | None) – Path to config directory or file. If None, resets to auto-discovery.

Return type:

None

get_config_path()[source]

Get current config path.

Returns:

Path to config directory if set, None otherwise

Return type:

Path | None

aiecs.config.tool_config.get_tool_config_loader()[source]

Get the global tool configuration loader instance.

Returns:

Global singleton instance

Return type:

ToolConfigLoader

Base Tool

class aiecs.tools.base_tool.BaseTool[source]

Bases: object

Base class for all tools, providing common functionality: - Input validation with Pydantic schemas - Caching with TTL and content-based keys - Concurrency with async/sync execution - Error handling with retries and context - Performance optimization with metrics - Logging with structured output

Tools inheriting from this class focus on business logic, leveraging the executor’s cross-cutting concerns.

Example

class MyTool(BaseTool):
class ReadSchema(BaseModel):

path: str

@validate_input(ReadSchema) @cache_result(ttl=300) @run_in_executor @measure_execution_time @sanitize_input def read(self, path: str):

# Implementation pass

__init__(config=None, tool_name=None)[source]

Initialize the tool with optional configuration.

Configuration is automatically loaded from: 1. Explicit config dict (highest priority) 2. YAML config files (config/tools/{tool_name}.yaml or config/tools.yaml) 3. Environment variables (via dotenv from .env files) 4. Tool defaults (lowest priority)

Parameters:
  • config (Dict[str, Any], optional) – Tool-specific configuration that overrides all other sources. If None, configuration is loaded automatically.

  • tool_name (str, optional) – Registered tool name. If None, uses class name.

Raises:
property settings: Any

Backward-compatible alias for validated tool configuration (tests, legacy callers).

get_schema_coverage()[source]

Get schema coverage metrics for this tool.

Returns:

  • total_methods: Total number of public methods

  • manual_schemas: Number of manually defined schemas

  • auto_generated_schemas: Number of auto-generated schemas

  • missing_schemas: Number of methods without schemas

  • coverage_percentage: Percentage of methods with schemas

  • quality_metrics: Quality metrics for schemas

Return type:

Dictionary with coverage metrics

run(op, **kwargs)[source]

Execute a synchronous operation with parameters.

Parameters:
  • op (str) – The name of the operation to execute.

  • **kwargs – The parameters to pass to the operation.

Returns:

The result of the operation.

Return type:

Any

Raises:
  • ToolExecutionError – If the operation fails.

  • InputValidationError – If input parameters are invalid.

  • SecurityError – If inputs contain malicious content.

async run_async(op, **kwargs)[source]

Execute an asynchronous operation with parameters.

Parameters:
  • op (str) – The name of the operation to execute.

  • **kwargs – The parameters to pass to the operation.

Returns:

The result of the operation.

Return type:

Any

Raises:
  • ToolExecutionError – If the operation fails.

  • InputValidationError – If input parameters are invalid.

  • SecurityError – If inputs contain malicious content.

async run_batch(operations)[source]

Execute multiple operations in parallel.

Parameters:

operations (List[Dict[str, Any]]) – List of operation dictionaries with ‘op’ and ‘kwargs’.

Returns:

List of operation results.

Return type:

List[Any]

Raises:
  • ToolExecutionError – If any operation fails.

  • InputValidationError – If input parameters are invalid.

Document Tools

Document Parser

class aiecs.tools.docs.document_parser_tool.DocumentType[source]

Bases: str, Enum

Supported document types for parsing

PDF = 'pdf'
DOCX = 'docx'
XLSX = 'xlsx'
PPTX = 'pptx'
TXT = 'txt'
HTML = 'html'
RTF = 'rtf'
CSV = 'csv'
JSON = 'json'
XML = 'xml'
MARKDOWN = 'md'
IMAGE = 'image'
UNKNOWN = 'unknown'
__new__(value)
class aiecs.tools.docs.document_parser_tool.ParsingStrategy[source]

Bases: str, Enum

Document parsing strategies

TEXT_ONLY = 'text_only'
STRUCTURED = 'structured'
FULL_CONTENT = 'full_content'
METADATA_ONLY = 'metadata_only'
__new__(value)
class aiecs.tools.docs.document_parser_tool.OutputFormat[source]

Bases: str, Enum

Output formats for parsed content

TEXT = 'text'
JSON = 'json'
MARKDOWN = 'markdown'
HTML = 'html'
__new__(value)
exception aiecs.tools.docs.document_parser_tool.DocumentParserError[source]

Bases: Exception

Base exception for document parser errors

exception aiecs.tools.docs.document_parser_tool.UnsupportedDocumentError[source]

Bases: DocumentParserError

Raised when document type is not supported

exception aiecs.tools.docs.document_parser_tool.DownloadError[source]

Bases: DocumentParserError

Raised when document download fails

exception aiecs.tools.docs.document_parser_tool.ParseError[source]

Bases: DocumentParserError

Raised when document parsing fails

class aiecs.tools.docs.document_parser_tool.DocumentParserTool[source]

Bases: BaseTool

Modern high-performance document parsing component that can: 1. Auto-detect document types from URLs or files 2. Download documents from URLs 3. Parse various document formats using existing atomic tools 4. Output structured content for AI consumption

Leverages existing tools: - ScraperTool for URL downloading - OfficeTool for Office document parsing - ImageTool for image OCR

Configuration: Configuration is automatically loaded by BaseTool from: 1. Explicit config dict (highest priority) - passed to constructor 2. YAML config files - config/tools/document_parser_tool.yaml or config/tools.yaml (see examples/config/tools/ for examples) 3. Environment variables - from .env files via dotenv (DOC_PARSER_ prefix) 4. Tool defaults - defined in Config class Field defaults (lowest priority)

Example usage:

# Basic usage (automatic configuration) tool = get_tool(“document_parser”)

# With explicit config override tool = get_tool(“document_parser”, config={“timeout”: 120})

# Configuration files: # - Runtime config: config/tools/document_parser_tool.yaml (see examples/config/tools/ for examples) # - Sensitive config: .env file with DOC_PARSER_* variables

See docs/developer/TOOLS/TOOL_CONFIGURATION_EXAMPLES.md for more examples.

class Config[source]

Bases: BaseSettings

Configuration for the document parser tool

Configuration is automatically loaded by BaseTool using ToolConfigLoader. Supports loading from: - YAML files: config/tools/document_parser_tool.yaml (see examples/config/tools/ for examples) - Environment variables: DOC_PARSER_* (from .env files via dotenv) - Explicit config dict: passed to constructor

Environment variable prefix: DOC_PARSER_ Example: DOC_PARSER_GCS_PROJECT_ID -> gcs_project_id Example: DOC_PARSER_TIMEOUT -> timeout

model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': 'DOC_PARSER_', 'env_prefix_target': 'variable', 'extra': 'forbid', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

user_agent: str
max_file_size: int
temp_dir: str
default_encoding: str
timeout: int
max_pages: int
enable_cloud_storage: bool
gcs_bucket_name: str | None
gcs_project_id: str | None
__init__(config=None, **kwargs)[source]

Initialize DocumentParserTool with settings

Configuration is automatically loaded by BaseTool from: 1. Explicit config dict (highest priority) 2. YAML config files (config/tools/document_parser_tool.yaml) 3. Environment variables (via dotenv from .env files) 4. Tool defaults (lowest priority)

Parameters:
  • config (Dict | None) – Optional configuration overrides

  • **kwargs – Additional arguments passed to BaseTool (e.g., tool_name)

class Parse_documentSchema[source]

Bases: BaseModel

Schema for parse_document operation

source: str
strategy: ParsingStrategy
output_format: OutputFormat
force_type: DocumentType | None
extract_metadata: bool
chunk_size: int | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Detect_document_typeSchema[source]

Bases: BaseModel

Schema for detect_document_type operation

source: str
download_sample: bool
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

detect_document_type(source, download_sample=True)[source]

Detect document type from URL or file path

Parameters:
  • source (str) – URL or file path

  • download_sample (bool) – Whether to download sample for content analysis

Returns:

Dict containing detected type and confidence

Return type:

Dict[str, Any]

parse_document(source, strategy=ParsingStrategy.FULL_CONTENT, output_format=OutputFormat.JSON, force_type=None, extract_metadata=True, chunk_size=None)[source]

Parse document from URL or file path

Parameters:
  • source (str) – URL or file path to document

  • strategy (ParsingStrategy) – Parsing strategy to use

  • output_format (OutputFormat) – Format for output content

  • force_type (DocumentType | None) – Force specific document type

  • extract_metadata (bool) – Whether to extract metadata

  • chunk_size (int | None) – Chunk size for large documents

Returns:

Dict containing parsed content and metadata

Return type:

Dict[str, Any]

async parse_document_async(source, strategy=ParsingStrategy.FULL_CONTENT, output_format=OutputFormat.JSON, force_type=None, extract_metadata=True, chunk_size=None)[source]

Async version of parse_document

Parameters:
Return type:

Dict[str, Any]

aiecs.tools.docs.document_parser_tool.DocumentParserSettings

alias of Config

Document Creator

Document Creator Tool

This tool is responsible for creating new documents from templates, initializing document structure, and managing document metadata.

Key Features: 1. Template-based document creation 2. Document structure initialization 3. Metadata management (title, author, date, etc.) 4. Style configuration and presets 5. Multi-format support (MD, HTML, DOCX, PDF, etc.)

class aiecs.tools.docs.document_creator_tool.DocumentType[source]

Bases: str, Enum

Supported document types

REPORT = 'report'
ARTICLE = 'article'
PRESENTATION = 'presentation'
MANUAL = 'manual'
LETTER = 'letter'
PROPOSAL = 'proposal'
ACADEMIC = 'academic'
TECHNICAL = 'technical'
CREATIVE = 'creative'
CUSTOM = 'custom'
__new__(value)
class aiecs.tools.docs.document_creator_tool.DocumentFormat[source]

Bases: str, Enum

Supported output formats

MARKDOWN = 'markdown'
HTML = 'html'
DOCX = 'docx'
PDF = 'pdf'
LATEX = 'latex'
PLAIN_TEXT = 'txt'
JSON = 'json'
XML = 'xml'
PPTX = 'pptx'
PPT = 'ppt'
__new__(value)
class aiecs.tools.docs.document_creator_tool.TemplateType[source]

Bases: str, Enum

Document template types

BLANK = 'blank'
BUSINESS_REPORT = 'business_report'
TECHNICAL_DOC = 'technical_doc'
ACADEMIC_PAPER = 'academic_paper'
PROJECT_PROPOSAL = 'project_proposal'
USER_MANUAL = 'user_manual'
PRESENTATION = 'presentation'
NEWSLETTER = 'newsletter'
INVOICE = 'invoice'
CUSTOM = 'custom'
__new__(value)
class aiecs.tools.docs.document_creator_tool.StylePreset[source]

Bases: str, Enum

Style presets for documents

DEFAULT = 'default'
CORPORATE = 'corporate'
ACADEMIC = 'academic'
MODERN = 'modern'
CLASSIC = 'classic'
MINIMAL = 'minimal'
COLORFUL = 'colorful'
PROFESSIONAL = 'professional'
__new__(value)
exception aiecs.tools.docs.document_creator_tool.DocumentCreatorError[source]

Bases: Exception

Base exception for Document Creator errors

exception aiecs.tools.docs.document_creator_tool.TemplateError[source]

Bases: DocumentCreatorError

Raised when template operations fail

exception aiecs.tools.docs.document_creator_tool.DocumentCreationError[source]

Bases: DocumentCreatorError

Raised when document creation fails

class aiecs.tools.docs.document_creator_tool.DocumentCreatorTool[source]

Bases: BaseTool

Document Creator Tool for creating new documents from templates

This tool provides: 1. Template management and selection 2. Document structure initialization 3. Metadata configuration 4. Style and format setup 5. Multi-format document creation

Integrates with: - DocumentWriterTool for content writing - DocumentLayoutTool for layout configuration - ContentInsertionTool for complex content

class Config[source]

Bases: BaseSettings

Configuration for the document creator tool

Automatically reads from environment variables with DOC_CREATOR_ prefix. Example: DOC_CREATOR_TEMPLATES_DIR -> templates_dir

model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': 'DOC_CREATOR_', 'env_prefix_target': 'variable', 'extra': 'forbid', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

templates_dir: str
output_dir: str
default_format: str
default_style: str
auto_backup: bool
include_metadata: bool
generate_toc: bool
__init__(config=None, **kwargs)[source]

Initialize Document Creator Tool with settings

Configuration is automatically loaded by BaseTool from: 1. Explicit config dict (highest priority) 2. YAML config files (config/tools/document_creator.yaml) 3. Environment variables (via dotenv from .env files) 4. Tool defaults (lowest priority)

Parameters:
  • config (Dict | None) – Optional configuration overrides

  • **kwargs – Additional arguments passed to BaseTool (e.g., tool_name)

class Create_documentSchema[source]

Bases: BaseModel

Schema for create_document operation

document_type: DocumentType
template_type: TemplateType
output_format: DocumentFormat
metadata: Dict[str, Any]
style_preset: StylePreset | None
output_path: str | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Create_from_templateSchema[source]

Bases: BaseModel

Schema for create_from_template operation

template_name: str
template_variables: Dict[str, Any]
output_format: DocumentFormat
output_path: str | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Setup_document_structureSchema[source]

Bases: BaseModel

Schema for setup_document_structure operation

document_path: str
sections: List[Dict[str, Any]]
generate_toc: bool
numbering_style: str | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Configure_metadataSchema[source]

Bases: BaseModel

Schema for configure_metadata operation

document_path: str
metadata: Dict[str, Any]
format_specific: bool
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Get_template_infoSchema[source]

Bases: BaseModel

Schema for get_template_info operation

template_type: TemplateType
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

create_document(document_type, template_type, output_format, metadata, style_preset=None, output_path=None)[source]

Create a new document from template

Parameters:
  • document_type (DocumentType) – Type of document to create

  • template_type (TemplateType) – Template to use

  • output_format (DocumentFormat) – Output format for the document

  • metadata (Dict[str, Any]) – Document metadata (title, author, etc.)

  • style_preset (StylePreset | None) – Style preset to apply

  • output_path (str | None) – Custom output path

Returns:

Dict containing document creation results

Return type:

Dict[str, Any]

create_from_template(template_name, template_variables, output_format, output_path=None)[source]

Create document from custom template with variables

Parameters:
  • template_name (str) – Name of template file

  • template_variables (Dict[str, Any]) – Variables to substitute in template

  • output_format (DocumentFormat) – Output format

  • output_path (str | None) – Custom output path

Returns:

Dict containing creation results

Return type:

Dict[str, Any]

setup_document_structure(document_path, sections, generate_toc=True, numbering_style=None)[source]

Setup document structure with sections and headers

Parameters:
  • document_path (str) – Path to document

  • sections (List[Dict[str, Any]]) – List of section configurations

  • generate_toc (bool) – Whether to generate table of contents

  • numbering_style (str | None) – Section numbering style

Returns:

Dict containing structure setup results

Return type:

Dict[str, Any]

configure_metadata(document_path, metadata, format_specific=True)[source]

Configure document metadata

Parameters:
  • document_path (str) – Path to document

  • metadata (Dict[str, Any]) – Metadata to configure

  • format_specific (bool) – Use format-specific metadata syntax

Returns:

Dict containing metadata configuration results

Return type:

Dict[str, Any]

list_templates()[source]

List available document templates

Returns:

Dict containing available templates

Return type:

Dict[str, Any]

get_template_info(template_type)[source]

Get information about a specific template

Parameters:

template_type (TemplateType) – Type of template

Returns:

Dict containing template information

Return type:

Dict[str, Any]

get_created_documents()[source]

Get list of documents created in this session

Returns:

List of created document information

Return type:

List[Dict[str, Any]]

aiecs.tools.docs.document_creator_tool.DocumentCreatorSettings

alias of Config

Document Writer

class aiecs.tools.docs.document_writer_tool.DocumentFormat[source]

Bases: str, Enum

Supported document formats for writing

TXT = 'txt'
PLAIN_TEXT = 'txt'
JSON = 'json'
CSV = 'csv'
XML = 'xml'
MARKDOWN = 'markdown'
HTML = 'html'
YAML = 'yaml'
PDF = 'pdf'
DOCX = 'docx'
XLSX = 'xlsx'
PPTX = 'pptx'
PPT = 'ppt'
BINARY = 'binary'
__new__(value)
class aiecs.tools.docs.document_writer_tool.WriteMode[source]

Bases: str, Enum

Document writing modes

CREATE = 'create'
OVERWRITE = 'overwrite'
APPEND = 'append'
UPDATE = 'update'
BACKUP_WRITE = 'backup_write'
VERSION_WRITE = 'version_write'
INSERT = 'insert'
REPLACE = 'replace'
DELETE = 'delete'
__new__(value)
class aiecs.tools.docs.document_writer_tool.EditOperation[source]

Bases: str, Enum

Advanced edit operations

BOLD = 'bold'
ITALIC = 'italic'
UNDERLINE = 'underline'
STRIKETHROUGH = 'strikethrough'
HIGHLIGHT = 'highlight'
INSERT_TEXT = 'insert_text'
DELETE_TEXT = 'delete_text'
REPLACE_TEXT = 'replace_text'
COPY_TEXT = 'copy_text'
CUT_TEXT = 'cut_text'
PASTE_TEXT = 'paste_text'
FIND_REPLACE = 'find_replace'
INSERT_LINE = 'insert_line'
DELETE_LINE = 'delete_line'
MOVE_LINE = 'move_line'
__new__(value)
class aiecs.tools.docs.document_writer_tool.EncodingType[source]

Bases: str, Enum

Text encoding types

UTF8 = 'utf-8'
UTF16 = 'utf-16'
ASCII = 'ascii'
GBK = 'gbk'
AUTO = 'auto'
__new__(value)
class aiecs.tools.docs.document_writer_tool.ValidationLevel[source]

Bases: str, Enum

Content validation levels

NONE = 'none'
BASIC = 'basic'
STRICT = 'strict'
ENTERPRISE = 'enterprise'
__new__(value)
exception aiecs.tools.docs.document_writer_tool.DocumentWriterError[source]

Bases: Exception

Base exception for document writer errors

exception aiecs.tools.docs.document_writer_tool.WriteError[source]

Bases: DocumentWriterError

Raised when write operations fail

exception aiecs.tools.docs.document_writer_tool.ValidationError[source]

Bases: DocumentWriterError

Raised when validation fails

exception aiecs.tools.docs.document_writer_tool.SecurityError[source]

Bases: DocumentWriterError

Raised when security validation fails

exception aiecs.tools.docs.document_writer_tool.WritePermissionError[source]

Bases: DocumentWriterError

Raised when write permission is denied

exception aiecs.tools.docs.document_writer_tool.ContentValidationError[source]

Bases: DocumentWriterError

Raised when content validation fails

exception aiecs.tools.docs.document_writer_tool.StorageError[source]

Bases: DocumentWriterError

Raised when storage operations fail

class aiecs.tools.docs.document_writer_tool.DocumentWriterTool[source]

Bases: BaseTool

Modern high-performance document writing component that can: 1. Handle multiple document formats and encodings 2. Provide production-grade write operations with validation 3. Support various write modes (create, overwrite, append, update) 4. Implement backup and versioning strategies 5. Ensure atomic operations and data integrity 6. Support both local and cloud storage

Production Features: - Atomic writes (no partial writes) - Content validation and security scanning - Automatic backup and versioning - Write permission and quota checks - Transaction-like operations - Audit logging

class Config[source]

Bases: BaseSettings

Configuration for the document writer tool

Automatically reads from environment variables with DOC_WRITER_ prefix. Example: DOC_WRITER_GCS_PROJECT_ID -> gcs_project_id

model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': 'DOC_WRITER_', 'env_prefix_target': 'variable', 'extra': 'forbid', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

temp_dir: str
backup_dir: str
output_dir: str | None
max_file_size: int
max_backup_versions: int
default_encoding: str
enable_backup: bool
enable_versioning: bool
enable_content_validation: bool
enable_security_scan: bool
atomic_write: bool
validation_level: str
timeout_seconds: int
auto_backup: bool
atomic_writes: bool
default_format: str
version_control: bool
security_scan: bool
enable_cloud_storage: bool
gcs_bucket_name: str | None
gcs_project_id: str | None
__init__(config=None, **kwargs)[source]

Initialize DocumentWriterTool with settings

Configuration is automatically loaded by BaseTool from: 1. Explicit config dict (highest priority) 2. YAML config files (config/tools/document_writer_tool.yaml) 3. Environment variables (via dotenv from .env files) 4. Tool defaults (lowest priority)

Parameters:
  • config (Dict | None) – Optional configuration overrides

  • **kwargs – Additional arguments passed to BaseTool (e.g., tool_name)

class Write_documentSchema[source]

Bases: BaseModel

Schema for write_document operation

target_path: str
content: str | bytes | Dict | List
format: DocumentFormat
mode: WriteMode
encoding: EncodingType
validation_level: ValidationLevel
metadata: Dict[str, Any] | None
backup_comment: str | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Batch_write_documentsSchema[source]

Bases: BaseModel

Schema for batch_write_documents operation

write_operations: List[Dict[str, Any]]
transaction_mode: bool
rollback_on_error: bool
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Edit_documentSchema[source]

Bases: BaseModel

Schema for edit_document operation

target_path: str
operation: EditOperation
content: str | None
position: Dict[str, Any] | None
selection: Dict[str, Any] | None
format_options: Dict[str, Any] | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Format_textSchema[source]

Bases: BaseModel

Schema for format_text operation

target_path: str
text_to_format: str
format_type: EditOperation
format_options: Dict[str, Any] | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Find_replaceSchema[source]

Bases: BaseModel

Schema for find_replace operation with precise control

target_path: str
find_text: str
replace_text: str
replace_all: bool
occurrence: int | None
start_line: int | None
end_line: int | None
case_sensitive: bool
regex_mode: bool
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Search_replace_blocksSchema[source]

Bases: BaseModel

Schema for search_replace_blocks operation (Cline/Claude Code format)

target_path: str
blocks: str
case_sensitive: bool
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

write_document(target_path, content, format, mode=WriteMode.CREATE, encoding=EncodingType.UTF8, validation_level=ValidationLevel.BASIC, metadata=None, backup_comment=None)[source]

Write document with production-grade features

Parameters:
  • target_path (str) – Target file path (local or cloud)

  • content (str | bytes | Dict | List) – Content to write

  • format (DocumentFormat) – Document format

  • mode (WriteMode) – Write mode (create, overwrite, append, update, etc.)

  • encoding (EncodingType) – Text encoding

  • validation_level (ValidationLevel) – Content validation level

  • metadata (Dict[str, Any] | None) – Additional metadata

  • backup_comment (str | None) – Comment for backup

Returns:

Dict containing write results and metadata

Return type:

Dict[str, Any]

async write_document_async(target_path, content, format, mode=WriteMode.CREATE, encoding=EncodingType.UTF8, validation_level=ValidationLevel.BASIC, metadata=None, backup_comment=None)[source]

Async version of write_document

Parameters:
Return type:

Dict[str, Any]

batch_write_documents(write_operations, transaction_mode=True, rollback_on_error=True)[source]

Batch write multiple documents with transaction support

Parameters:
  • write_operations (List[Dict[str, Any]]) – List of write operation dictionaries

  • transaction_mode (bool) – Use transaction mode for atomicity

  • rollback_on_error (bool) – Rollback all operations on any error

Returns:

Dict containing batch write results

Return type:

Dict[str, Any]

edit_document(target_path, operation, content=None, position=None, selection=None, format_options=None)[source]

Perform advanced editing operations on documents

Parameters:
  • target_path (str) – Target file path

  • operation (EditOperation) – Edit operation to perform

  • content (str | None) – Content for the operation (if applicable)

  • position (Dict[str, Any] | None) – Position info (line, column, offset)

  • selection (Dict[str, Any] | None) – Text selection range

  • format_options (Dict[str, Any] | None) – Additional format options

Returns:

Dict containing edit results

Return type:

Dict[str, Any]

format_text(target_path, text_to_format, format_type, format_options=None)[source]

Apply formatting to specific text in a document

Parameters:
  • target_path (str) – Target file path

  • text_to_format (str) – Text to apply formatting to

  • format_type (EditOperation) – Type of formatting (bold, italic, etc.)

  • format_options (Dict[str, Any] | None) – Additional format options

Returns:

Dict containing formatting results

Return type:

Dict[str, Any]

find_replace(target_path, find_text, replace_text, replace_all=False, occurrence=None, start_line=None, end_line=None, case_sensitive=True, regex_mode=False)[source]

Find and replace text in a document with precise control

Parameters:
  • target_path (str) – Target file path

  • find_text (str) – Text to find

  • replace_text (str) – Text to replace with

  • replace_all (bool) – Replace all occurrences (ignored if occurrence is set)

  • occurrence (int | None) – Replace only the nth occurrence (1-based index). If None, uses replace_all

  • start_line (int | None) – Start line number (1-based, inclusive) to limit search range

  • end_line (int | None) – End line number (1-based, inclusive) to limit search range

  • case_sensitive (bool) – Case sensitive search

  • regex_mode (bool) – Use regex for find/replace

Returns:

  • target_path: Path to the file

  • find_text: Text that was searched for

  • replace_text: Replacement text

  • replacements_made: Number of replacements made

  • occurrence_replaced: Which occurrence was replaced (if occurrence was specified)

  • line_range: Line range used (if specified)

  • write_result: Result of the write operation

Return type:

Dict containing find/replace results including

Examples

# Replace first occurrence find_replace(path, “old”, “new”, replace_all=False)

# Replace all occurrences find_replace(path, “old”, “new”, replace_all=True)

# Replace 3rd occurrence only find_replace(path, “old”, “new”, occurrence=3)

# Replace all occurrences in lines 10-50 find_replace(path, “old”, “new”, replace_all=True, start_line=10, end_line=50)

# Replace 2nd occurrence in lines 10-50 find_replace(path, “old”, “new”, occurrence=2, start_line=10, end_line=50)

search_replace_blocks(target_path, blocks, case_sensitive=True)[source]

Parse and execute SEARCH/REPLACE blocks (Cline/Claude Code format)

This method accepts a string containing one or more SEARCH/REPLACE blocks and executes them sequentially. This format is commonly used by AI coding assistants like Cline and Claude Code.

Parameters:
  • target_path (str) – Target file path

  • blocks (str) – String containing SEARCH/REPLACE blocks

  • case_sensitive (bool) – Case sensitive search (default: True)

Returns:

Dict containing results of all replacements

Return type:

Dict[str, Any]

Format:

<<<<<<< SEARCH old text to find ======= new text to replace with >>>>>>> REPLACE

Multiple blocks can be provided in sequence.

Example

blocks = ‘’’ <<<<<<< SEARCH def old_function():

pass

def new_function():

return True

>>>>>>> REPLACE

<<<<<<< SEARCH OLD_CONSTANT = 1 ======= NEW_CONSTANT = 2 >>>>>>> REPLACE ‘’’

result = tool.search_replace_blocks(“file.py”, blocks)

aiecs.tools.docs.document_writer_tool.DocumentWriterSettings

alias of Config

Search Tool

Enhanced Search Tool Package

Deprecated since version 2026-07-01: Built-in search tools in aiecs.tools.search_tool are being migrated to MCP server services and will be removed on 2026-07-01. Importing this package emits a DeprecationWarning; please migrate to the corresponding MCP server tools.

A comprehensive, production-ready web search tool that integrates Google Custom Search API with advanced features including:

  • Result quality scoring and ranking

  • Query intent analysis and optimization

  • Result deduplication

  • Context-aware search with history tracking

  • Intelligent Redis caching with intent-aware TTL

  • Comprehensive metrics and monitoring

  • Agent-friendly error handling

Features: - Multiple search types: web, image, news, video - Dual authentication: API key and service account - Rate limiting with token bucket algorithm - Circuit breaker pattern for API resilience - Intelligent caching with Redis backend - Quality analysis with authority, relevance, and freshness scoring - Query enhancement based on detected intent - Structured result summaries - Search context tracking and preference learning - Enhanced metrics and health scoring - Agent-optimized error messages with actionable suggestions

Usage:

from aiecs.tools.search_tool import SearchTool

# Create search tool instance search_tool = SearchTool()

# Perform enhanced web search results = search_tool.search_web(

query=”machine learning tutorial”, auto_enhance=True, return_summary=True

)

# Access results and quality analysis for result in results[‘results’]:

print(f”Title: {result[‘title’]}”) print(f”Quality: {result[‘_quality_summary’][‘score’]:.2f}”) print(f”Credibility: {result[‘_quality_summary’][‘level’]}”)

# Check metrics print(search_tool.get_metrics_report())

class aiecs.tools.search_tool.SearchTool[source]

Bases: BaseTool

Enhanced web search tool using Google Custom Search API.

Provides intelligent search with: - Quality scoring and ranking - Query intent analysis - Result deduplication - Context-aware search - Intelligent Redis caching - Comprehensive metrics - Agent-friendly error handling

class Config[source]

Bases: BaseSettings

Configuration for the search tool

Automatically reads from environment variables with SEARCH_TOOL_ prefix. Example: SEARCH_TOOL_GOOGLE_API_KEY -> google_api_key

Sensitive fields (API keys, credentials) are loaded from .env files via dotenv.

model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': 'SEARCH_TOOL_', 'env_prefix_target': 'variable', 'extra': 'forbid', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

google_api_key: str | None
google_cse_id: str | None
google_application_credentials: str | None
max_results_per_query: int
cache_ttl: int
rate_limit_requests: int
rate_limit_window: int
circuit_breaker_threshold: int
circuit_breaker_timeout: int
retry_attempts: int
retry_backoff: float
timeout: int
user_agent: str
enable_quality_analysis: bool
enable_intent_analysis: bool
enable_deduplication: bool
enable_context_tracking: bool
enable_intelligent_cache: bool
similarity_threshold: float
max_search_history: int
class Search_webSchema[source]

Bases: BaseModel

Schema for search_web operation

query: str
num_results: int
start_index: int
language: str
country: str
date_restrict: str | None
file_type: str | None
exclude_terms: List[str] | None
auto_enhance: bool
return_summary: bool

Validate safe search level

Parameters:

v (str)

Return type:

str

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Search_imagesSchema[source]

Bases: BaseModel

Schema for search_images operation

query: str
num_results: int
image_size: str | None
image_type: str | None
image_color_type: str | None

Validate safe search level

Parameters:

v (str)

Return type:

str

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Search_newsSchema[source]

Bases: BaseModel

Schema for search_news operation

query: str
num_results: int
start_index: int
language: str
date_restrict: str | None
sort_by: str
classmethod validate_sort_by(v)[source]

Validate sort order

Parameters:

v (str)

Return type:

str

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Search_videosSchema[source]

Bases: BaseModel

Schema for search_videos operation

query: str
num_results: int
start_index: int
language: str

Validate safe search level

Parameters:

v (str)

Return type:

str

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Get_metricsSchema[source]

Bases: BaseModel

Schema for get_metrics operation (no parameters required)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Get_metrics_reportSchema[source]

Bases: BaseModel

Schema for get_metrics_report operation (no parameters required)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Get_health_scoreSchema[source]

Bases: BaseModel

Schema for get_health_score operation (no parameters required)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Get_quota_statusSchema[source]

Bases: BaseModel

Schema for get_quota_status operation (no parameters required)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class Get_search_contextSchema[source]

Bases: BaseModel

Schema for get_search_context operation (no parameters required)

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

description = 'Comprehensive web search tool using Google Custom Search API.'
category = 'task'
__init__(config=None, **kwargs)[source]

Initialize SearchTool with enhanced capabilities.

Parameters:
  • config (Dict[str, Any] | None) – Optional configuration overrides

  • **kwargs – Additional arguments passed to BaseTool (e.g., tool_name)

Raises:

Configuration is automatically loaded by BaseTool from: 1. Explicit config dict (highest priority) 2. YAML config files (config/tools/search.yaml) 3. Environment variables (via dotenv from .env files) 4. Tool defaults (lowest priority)

Sensitive fields (API keys, credentials) are loaded from .env files.

search_web(query, num_results=10, start_index=1, language='en', country='us', safe_search='medium', date_restrict=None, file_type=None, exclude_terms=None, auto_enhance=True, return_summary=False)[source]

Search the web with enhanced intelligence.

Parameters:
  • query (str) – Search query string

  • num_results (int) – Number of results to return

  • start_index (int) – Starting index for pagination

  • language (str) – Language code

  • country (str) – Country code

  • safe_search (str) – Safe search level

  • date_restrict (str | None) – Date restriction

  • file_type (str | None) – File type filter

  • exclude_terms (str | None) – Terms to exclude

  • auto_enhance (bool) – Enable automatic query enhancement

  • return_summary (bool) – Return summary metadata

Returns:

List of search results (or dict with results and summary)

Return type:

Dict[str, Any]

search_images(query, num_results=10, image_size=None, image_type=None, image_color_type=None, safe_search='medium')[source]

Search for images

Parameters:
  • query (str)

  • num_results (int)

  • image_size (str | None)

  • image_type (str | None)

  • image_color_type (str | None)

  • safe_search (str)

Return type:

List[Dict[str, Any]]

search_news(query, num_results=10, start_index=1, language='en', date_restrict=None, sort_by='date')[source]

Search for news articles

Parameters:
  • query (str)

  • num_results (int)

  • start_index (int)

  • language (str)

  • date_restrict (str | None)

  • sort_by (str)

Return type:

List[Dict[str, Any]]

search_videos(query, num_results=10, start_index=1, language='en', safe_search='medium')[source]

Search for videos

Parameters:
  • query (str)

  • num_results (int)

  • start_index (int)

  • language (str)

  • safe_search (str)

Return type:

List[Dict[str, Any]]

get_metrics()[source]

Get comprehensive metrics

Return type:

Dict[str, Any]

get_metrics_report()[source]

Get human-readable metrics report

Return type:

str

get_health_score()[source]

Get system health score (0-1)

Return type:

float

get_quota_status()[source]

Get quota and rate limit status

Return type:

Dict[str, Any]

get_search_context()[source]

Get search context information

Return type:

Dict[str, Any] | None

class aiecs.tools.search_tool.SearchType[source]

Bases: str, Enum

Supported search types

WEB = 'web'
IMAGE = 'image'
NEWS = 'news'
VIDEO = 'video'
__new__(value)
class aiecs.tools.search_tool.SafeSearch[source]

Bases: str, Enum

Safe search levels

OFF = 'off'
MEDIUM = 'medium'
HIGH = 'high'
__new__(value)
class aiecs.tools.search_tool.ImageSize[source]

Bases: str, Enum

Image size filters

ICON = 'icon'
SMALL = 'small'
MEDIUM = 'medium'
LARGE = 'large'
XLARGE = 'xlarge'
XXLARGE = 'xxlarge'
HUGE = 'huge'
__new__(value)
class aiecs.tools.search_tool.ImageType[source]

Bases: str, Enum

Image type filters

CLIPART = 'clipart'
FACE = 'face'
LINEART = 'lineart'
STOCK = 'stock'
PHOTO = 'photo'
ANIMATED = 'animated'
__new__(value)
class aiecs.tools.search_tool.ImageColorType[source]

Bases: str, Enum

Image color type filters

COLOR = 'color'
GRAY = 'gray'
MONO = 'mono'
TRANS = 'trans'
__new__(value)
class aiecs.tools.search_tool.QueryIntentType[source]

Bases: str, Enum

Query intent types

DEFINITION = 'definition'
HOW_TO = 'how_to'
COMPARISON = 'comparison'
FACTUAL = 'factual'
RECENT_NEWS = 'recent_news'
ACADEMIC = 'academic'
PRODUCT = 'product'
GENERAL = 'general'
__new__(value)
class aiecs.tools.search_tool.CredibilityLevel[source]

Bases: str, Enum

Result credibility levels

HIGH = 'high'
MEDIUM = 'medium'
LOW = 'low'
__new__(value)
class aiecs.tools.search_tool.CircuitState[source]

Bases: str, Enum

Circuit breaker states

CLOSED = 'closed'
OPEN = 'open'
HALF_OPEN = 'half_open'
__new__(value)
exception aiecs.tools.search_tool.SearchToolError[source]

Bases: Exception

Base exception for SearchTool errors

exception aiecs.tools.search_tool.AuthenticationError[source]

Bases: SearchToolError

Authentication-related errors

exception aiecs.tools.search_tool.QuotaExceededError[source]

Bases: SearchToolError

API quota exceeded

exception aiecs.tools.search_tool.RateLimitError[source]

Bases: SearchToolError

Rate limit exceeded

exception aiecs.tools.search_tool.CircuitBreakerOpenError[source]

Bases: SearchToolError

Circuit breaker is open

exception aiecs.tools.search_tool.SearchAPIError[source]

Bases: SearchToolError

Search API errors

exception aiecs.tools.search_tool.ValidationError[source]

Bases: SearchToolError

Input validation errors

exception aiecs.tools.search_tool.CacheError[source]

Bases: SearchToolError

Cache-related errors

API Source Tool

API Source Tool