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:
objectSingleton 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
- 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)
- 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.
- 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:
- validate_config(config_dict, config_schema)[source]
Validate merged config against tool’s Pydantic schema.
- 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:
- Returns:
Merged and validated configuration dictionary
- Raises:
ValidationError – If config_schema is provided and validation fails
- Return type:
Base Tool
- class aiecs.tools.base_tool.BaseTool[source]
Bases:
objectBase 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:
- Raises:
ValueError – If config is invalid.
ValidationError – If config validation fails (when Config class exists).
- 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]
-
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]
-
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]
-
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:
ExceptionBase exception for document parser errors
- exception aiecs.tools.docs.document_parser_tool.UnsupportedDocumentError[source]
Bases:
DocumentParserErrorRaised when document type is not supported
- exception aiecs.tools.docs.document_parser_tool.DownloadError[source]
Bases:
DocumentParserErrorRaised when document download fails
- exception aiecs.tools.docs.document_parser_tool.ParseError[source]
Bases:
DocumentParserErrorRaised when document parsing fails
- class aiecs.tools.docs.document_parser_tool.DocumentParserTool[source]
Bases:
BaseToolModern 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:
BaseSettingsConfiguration 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].
- __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:
BaseModelSchema for parse_document operation
- strategy: ParsingStrategy
- output_format: OutputFormat
- force_type: DocumentType | 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:
BaseModelSchema for detect_document_type operation
- 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
- 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:
- 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:
source (str)
strategy (ParsingStrategy)
output_format (OutputFormat)
force_type (DocumentType | None)
extract_metadata (bool)
chunk_size (int | None)
- Return type:
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]
-
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]
-
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]
-
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]
-
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:
ExceptionBase exception for Document Creator errors
- exception aiecs.tools.docs.document_creator_tool.TemplateError[source]
Bases:
DocumentCreatorErrorRaised when template operations fail
- exception aiecs.tools.docs.document_creator_tool.DocumentCreationError[source]
Bases:
DocumentCreatorErrorRaised when document creation fails
- class aiecs.tools.docs.document_creator_tool.DocumentCreatorTool[source]
Bases:
BaseToolDocument 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:
BaseSettingsConfiguration 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].
- __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:
BaseModelSchema for create_document operation
- document_type: DocumentType
- template_type: TemplateType
- output_format: DocumentFormat
- style_preset: StylePreset | 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:
BaseModelSchema for create_from_template operation
- output_format: DocumentFormat
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Setup_document_structureSchema[source]
Bases:
BaseModelSchema for setup_document_structure operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Configure_metadataSchema[source]
Bases:
BaseModelSchema for configure_metadata operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Get_template_infoSchema[source]
Bases:
BaseModelSchema 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:
- create_from_template(template_name, template_variables, output_format, output_path=None)[source]
Create document from custom template with variables
- setup_document_structure(document_path, sections, generate_toc=True, numbering_style=None)[source]
Setup document structure with sections and headers
- Parameters:
- Returns:
Dict containing structure setup results
- Return type:
- configure_metadata(document_path, metadata, format_specific=True)[source]
Configure document metadata
- 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:
Document Writer
- class aiecs.tools.docs.document_writer_tool.DocumentFormat[source]
-
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]
-
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]
-
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]
-
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]
-
Content validation levels
- NONE = 'none'
- BASIC = 'basic'
- STRICT = 'strict'
- ENTERPRISE = 'enterprise'
- __new__(value)
- exception aiecs.tools.docs.document_writer_tool.DocumentWriterError[source]
Bases:
ExceptionBase exception for document writer errors
- exception aiecs.tools.docs.document_writer_tool.WriteError[source]
Bases:
DocumentWriterErrorRaised when write operations fail
- exception aiecs.tools.docs.document_writer_tool.ValidationError[source]
Bases:
DocumentWriterErrorRaised when validation fails
- exception aiecs.tools.docs.document_writer_tool.SecurityError[source]
Bases:
DocumentWriterErrorRaised when security validation fails
- exception aiecs.tools.docs.document_writer_tool.WritePermissionError[source]
Bases:
DocumentWriterErrorRaised when write permission is denied
- exception aiecs.tools.docs.document_writer_tool.ContentValidationError[source]
Bases:
DocumentWriterErrorRaised when content validation fails
- exception aiecs.tools.docs.document_writer_tool.StorageError[source]
Bases:
DocumentWriterErrorRaised when storage operations fail
- class aiecs.tools.docs.document_writer_tool.DocumentWriterTool[source]
Bases:
BaseToolModern 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:
BaseSettingsConfiguration 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].
- __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:
BaseModelSchema for write_document operation
- format: DocumentFormat
- encoding: EncodingType
- validation_level: ValidationLevel
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Batch_write_documentsSchema[source]
Bases:
BaseModelSchema for batch_write_documents operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Edit_documentSchema[source]
Bases:
BaseModelSchema for edit_document operation
- operation: EditOperation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Format_textSchema[source]
Bases:
BaseModelSchema for format_text operation
- format_type: EditOperation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Find_replaceSchema[source]
Bases:
BaseModelSchema for find_replace operation with precise control
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Search_replace_blocksSchema[source]
Bases:
BaseModelSchema for search_replace_blocks operation (Cline/Claude Code format)
- 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)
format (DocumentFormat) – Document format
mode (WriteMode) – Write mode (create, overwrite, append, update, etc.)
encoding (EncodingType) – Text encoding
validation_level (ValidationLevel) – Content validation level
backup_comment (str | None) – Comment for backup
- Returns:
Dict containing write results and metadata
- Return type:
- 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
- batch_write_documents(write_operations, transaction_mode=True, rollback_on_error=True)[source]
Batch write multiple documents with transaction support
- edit_document(target_path, operation, content=None, position=None, selection=None, format_options=None)[source]
Perform advanced editing operations on documents
- Parameters:
- Returns:
Dict containing edit results
- Return type:
- format_text(target_path, text_to_format, format_type, format_options=None)[source]
Apply formatting to specific text in a document
- Parameters:
- Returns:
Dict containing formatting results
- Return type:
- 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:
- Returns:
Dict containing results of all replacements
- Return type:
- 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)
Search Tool
Enhanced Search Tool Package
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:
BaseToolEnhanced 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:
BaseSettingsConfiguration 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].
- class Search_webSchema[source]
Bases:
BaseModelSchema for search_web operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Search_imagesSchema[source]
Bases:
BaseModelSchema for search_images operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Search_newsSchema[source]
Bases:
BaseModelSchema for search_news operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Search_videosSchema[source]
Bases:
BaseModelSchema for search_videos operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Get_metricsSchema[source]
Bases:
BaseModelSchema 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:
BaseModelSchema 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:
BaseModelSchema 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:
BaseModelSchema 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:
BaseModelSchema 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:
- Raises:
AuthenticationError – If Google API libraries not available
ValidationError – If configuration is invalid
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:
- search_images(query, num_results=10, image_size=None, image_type=None, image_color_type=None, safe_search='medium')[source]
Search for images
- search_news(query, num_results=10, start_index=1, language='en', date_restrict=None, sort_by='date')[source]
Search for news articles
- class aiecs.tools.search_tool.SearchType[source]
-
Supported search types
- WEB = 'web'
- IMAGE = 'image'
- NEWS = 'news'
- VIDEO = 'video'
- __new__(value)
- class aiecs.tools.search_tool.SafeSearch[source]
-
Safe search levels
- OFF = 'off'
- MEDIUM = 'medium'
- HIGH = 'high'
- __new__(value)
- class aiecs.tools.search_tool.ImageSize[source]
-
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]
-
Image type filters
- CLIPART = 'clipart'
- FACE = 'face'
- LINEART = 'lineart'
- STOCK = 'stock'
- PHOTO = 'photo'
- ANIMATED = 'animated'
- __new__(value)
- class aiecs.tools.search_tool.ImageColorType[source]
-
Image color type filters
- COLOR = 'color'
- GRAY = 'gray'
- MONO = 'mono'
- TRANS = 'trans'
- __new__(value)
- class aiecs.tools.search_tool.QueryIntentType[source]
-
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]
-
Result credibility levels
- HIGH = 'high'
- MEDIUM = 'medium'
- LOW = 'low'
- __new__(value)
- class aiecs.tools.search_tool.CircuitState[source]
-
Circuit breaker states
- CLOSED = 'closed'
- OPEN = 'open'
- HALF_OPEN = 'half_open'
- __new__(value)
- exception aiecs.tools.search_tool.SearchToolError[source]
Bases:
ExceptionBase exception for SearchTool errors
- exception aiecs.tools.search_tool.AuthenticationError[source]
Bases:
SearchToolErrorAuthentication-related errors
- exception aiecs.tools.search_tool.QuotaExceededError[source]
Bases:
SearchToolErrorAPI quota exceeded
- exception aiecs.tools.search_tool.RateLimitError[source]
Bases:
SearchToolErrorRate limit exceeded
- exception aiecs.tools.search_tool.CircuitBreakerOpenError[source]
Bases:
SearchToolErrorCircuit breaker is open
- exception aiecs.tools.search_tool.SearchAPIError[source]
Bases:
SearchToolErrorSearch API errors
- exception aiecs.tools.search_tool.ValidationError[source]
Bases:
SearchToolErrorInput validation errors
- exception aiecs.tools.search_tool.CacheError[source]
Bases:
SearchToolErrorCache-related errors
API Source Tool
API Source Tool
API Source Tool
Unified interface for querying various external real-time API data sources including economic indicators, news, public databases, and custom APIs with plugin architecture.
Enhanced Features: - Auto-discovery of API providers - Unified query interface with intelligent parameter enhancement - Intelligent caching with TTL strategies - Cross-provider data fusion - Automatic fallback to alternative providers - Advanced search with relevance scoring - Comprehensive error handling with recovery suggestions - Detailed metrics and health monitoring
- exception aiecs.tools.apisource.tool.APISourceError[source]
Bases:
ExceptionBase exception for API Source Tool errors
- exception aiecs.tools.apisource.tool.ProviderNotFoundError[source]
Bases:
APISourceErrorRaised when requested provider is not found
- exception aiecs.tools.apisource.tool.APIRateLimitError[source]
Bases:
APISourceErrorRaised when API rate limit is exceeded
- exception aiecs.tools.apisource.tool.APIAuthenticationError[source]
Bases:
APISourceErrorRaised when API authentication fails
- class aiecs.tools.apisource.tool.APISourceTool[source]
Bases:
BaseToolQuery external real-time API data sources including economic indicators, news, public databases, and custom APIs.
Supports multiple data providers through a plugin architecture: - FRED: Federal Reserve Economic Data (US economic indicators) - World Bank: Global development indicators - News API: News articles and headlines - Census: US Census Bureau demographic and economic data
Provides unified interface with automatic rate limiting, caching, and error handling.
- class Config[source]
Bases:
BaseSettingsConfiguration for the API Source Tool
Automatically reads from environment variables with APISOURCE_TOOL_ prefix. Example: APISOURCE_TOOL_FRED_API_KEY -> fred_api_key
Sensitive fields (API keys) 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': 'APISOURCE_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].
- __init__(config=None, **kwargs)[source]
Initialize API Source Tool with enhanced intelligence features.
- Parameters:
Configuration is automatically loaded by BaseTool from: 1. Explicit config dict (highest priority) 2. YAML config files (config/tools/apisource.yaml) 3. Environment variables (via dotenv from .env files) 4. Tool defaults (lowest priority)
Sensitive fields (API keys) are loaded from .env files.
- class QuerySchema[source]
Bases:
BaseModelSchema for query operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class List_providersSchema[source]
Bases:
BaseModelSchema for list_providers operation (no parameters required)
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Get_provider_infoSchema[source]
Bases:
BaseModelSchema for get_provider_info operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class SearchSchema[source]
Bases:
BaseModelSchema for search operation
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class Get_metrics_reportSchema[source]
Bases:
BaseModelSchema 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].
- query(provider, operation, params, query_text=None, enable_fallback=None)[source]
Query a specific API provider with intelligent parameter enhancement and automatic fallback.
- Parameters:
provider (str) – API provider name (e.g., ‘fred’, ‘worldbank’, ‘newsapi’, ‘census’)
operation (str) – Provider-specific operation (e.g., ‘get_series’, ‘search_indicators’)
params (Dict[str, Any]) – Operation-specific parameters as dictionary
query_text (str | None) – Optional natural language query for intelligent parameter enhancement
enable_fallback (bool | None) – Override config setting for fallback (defaults to config value)
- Returns:
Dictionary containing response data with enhanced metadata
- Raises:
ProviderNotFoundError – If the specified provider is not available
ValueError – If operation or parameters are invalid
APISourceError – If the API request fails after all retries and fallbacks
- Return type:
- get_provider_info(provider)[source]
Get detailed information about a specific API provider.
- Parameters:
provider (str) – API provider name to get information about
- Returns:
Dictionary with provider metadata including name, description, operations, and configuration
- Raises:
ProviderNotFoundError – If the specified provider is not found
- Return type:
- search(query, providers=None, limit=10, enable_fusion=None, enable_enhancement=None, fusion_strategy='best_quality', search_options=None)[source]
Search across multiple API providers with intelligent fusion and enhancement.
- Parameters:
query (str) – Search query text to find relevant data
providers (List[str] | None) – List of provider names to search (searches all if not specified)
limit (int) – Maximum number of results to return per provider
enable_fusion (bool | None) – Override config for data fusion (defaults to config value)
enable_enhancement (bool | None) – Override config for search enhancement (defaults to config value)
fusion_strategy (str) – Strategy for data fusion (‘best_quality’, ‘merge_all’, ‘consensus’)
search_options (Dict[str, Any] | None) – Options for search enhancement: - relevance_threshold: Minimum relevance score (0-1) - sort_by: Sort method (‘relevance’, ‘popularity’, ‘recency’, ‘composite’) - max_results: Maximum results after enhancement
- Returns:
results: Enhanced and potentially fused search results
metadata: Search metadata including fusion info and query analysis
providers_queried: List of providers that were queried
- Return type:
Dictionary with