Internal Reference Document – This document provides comprehensive mapping of all files in the project, including their purposes, dependencies, relationships, imports, exports, and detailed information.
Note: This is a detailed internal reference for maintainers. For user-facing documentation, see README.md, ARCHITECTURE.md, and WORKFLOW.md.
- Entry Points
- Project Structure
- Module-by-Module File Mapping
- Detailed File Documentation
- Dependency Graph
- Data Flow
- Import Patterns Summary
| File | Purpose | Dependencies | Used By |
|---|---|---|---|
app.py |
Web Application Entry Point - Quart web server for SSE chat interface | flexiai.config.models, flexiai.config.logging_config, flexiai.controllers.quart_chat_controller |
Hypercorn server |
chat.py |
CLI Application Entry Point - Command-line chat interface | flexiai.config.models, flexiai.config.logging_config, flexiai.controllers.cli_chat_controller |
Direct execution |
flexiai-toolsmith/
├── app.py # Web entry point
├── chat.py # CLI entry point
├── flexiai/
│ ├── agents/ # Multi-agent system (experimental)
│ ├── channels/ # Event publishing channels
│ ├── config/ # Configuration management
│ ├── controllers/ # Application controllers
│ ├── core/ # Core event handling
│ ├── credentials/ # AI provider credentials
│ ├── database/ # Database models & connection
│ ├── toolsmith/ # Tool infrastructure
│ └── utils/ # Utility functions
├── templates/ # HTML templates
├── static/ # Static assets
└── logs/ # Log files
| File | Purpose | Dependencies | Exports |
|---|---|---|---|
models.py |
Pydantic Settings Models - Defines all environment variable models (OpenAI, Azure, DeepSeek, Qwen, GitHub, General) | pydantic_settings, pydantic |
OpenAISettings, AzureOpenAISettings, DeepSeekSettings, QwenSettings, GitHubAzureInferenceSettings, GeneralSettings |
client_settings.py |
Client Configuration - Validates and loads provider-specific settings | flexiai.config.models |
config (validated settings dict) |
client_factory.py |
Client Factory - Creates singleton AI client instances (sync/async) | flexiai.credentials.credentials |
get_client(), get_client_async() |
logging_config.py |
Logging Setup - Configures rotating file and console logging | logging, os |
setup_logging() |
Relationships:
models.py→ Used byclient_settings.pyclient_settings.py→ Used bycredentials.pyclient_factory.py→ Usescredentials.py→ Used by all controllerslogging_config.py→ Used byapp.py,chat.py
| File | Purpose | Dependencies | Exports |
|---|---|---|---|
credentials.py |
Credential Manager - Unified interface for all AI providers (OpenAI, Azure, DeepSeek, Qwen, GitHub) | flexiai.config.client_settings, openai |
get_client() - Returns configured OpenAI-compatible client |
Relationships:
- Uses
client_settings.pyto get provider config - Used by
client_factory.py - Creates the base AI client for all operations
| File | Purpose | Dependencies | Exports |
|---|---|---|---|
cli_chat_controller.py |
CLI Chat Controller - Manages command-line chat loop, user input/output | flexiai.config.client_factory, flexiai.core.handlers.*, flexiai.toolsmith.tools_manager, flexiai.core.events.event_bus, flexiai.channels.* |
CLIChatController class |
quart_chat_controller.py |
Web Chat Controller - Manages HTTP/SSE chat sessions, Blueprint routes | flexiai.config.*, flexiai.core.handlers.*, flexiai.toolsmith.tools_manager, flexiai.core.events.*, quart |
QuartChatController class, chat_bp Blueprint |
Relationships:
- Both controllers use:
client_factory.py→ Get AI clientrun_thread_manager.py→ Manage threads/runstools_manager.py→ Access toolshandler_factory.py→ Create event handlersevent_bus.py→ Publish eventschannel_manager.py→ Get active channels
cli_chat_controller.py→ Used bychat.pyquart_chat_controller.py→ Used byapp.py
| File | Purpose | Dependencies | Exports |
|---|---|---|---|
run_thread_manager.py |
Thread/Run Manager - Manages OpenAI Assistant API threads, runs, messages | openai client |
RunThreadManager class |
event_handler.py |
Event Handler - Processes streaming events, dispatches to handlers, manages tool calls | flexiai.core.handlers.tool_call_executor, flexiai.core.handlers.run_thread_manager, flexiai.core.handlers.event_dispatcher, flexiai.core.events.*, flexiai.channels.multi_channel_publisher |
EventHandler class |
event_dispatcher.py |
Event Dispatcher - Routes events to appropriate handlers based on event type | flexiai.core.events.event_models |
EventDispatcher class |
handler_factory.py |
Handler Factory - Creates EventHandler instances with proper wiring | flexiai.core.handlers.event_handler, flexiai.core.handlers.run_thread_manager, flexiai.core.handlers.event_dispatcher |
create_event_handler() function |
tool_call_executor.py |
Tool Call Executor - Executes tool calls from AI assistant | flexiai.toolsmith.tools_registry, flexiai.utils.context_utils |
ToolCallExecutor class |
Relationships:
run_thread_manager.py→ Used by all controllers, event_handler, tools_managerevent_handler.py→ Uses all other handlers, publishes to channelsevent_dispatcher.py→ Used by event_handlerhandler_factory.py→ Creates event_handler instancestool_call_executor.py→ Uses tools_registry → Executes tools
| File | Purpose | Dependencies | Exports |
|---|---|---|---|
event_models.py |
Event Models - Pydantic models for all event types (MessageDelta, ThreadRun, etc.) | pydantic |
Event model classes |
event_bus.py |
Event Bus - Pub/sub system for events (singleton) | None | global_event_bus instance |
sse_manager.py |
SSE Manager - Manages Server-Sent Events for web clients | threading, collections |
SSEManager class, global_sse_manager |
session.py |
Chat Session - Manages chat session state | flexiai.core.events.rolling_event_buffer |
ChatSession class |
rolling_event_buffer.py |
Rolling Buffer - Maintains rolling buffer of recent events | collections |
RollingEventBuffer class |
Relationships:
event_models.py→ Used by all event-related modulesevent_bus.py→ Used by controllers, event_handler, channelssse_manager.py→ Used by quart_channel, quart_chat_controllersession.py→ Uses rolling_event_buffer- All event modules → Used by event_handler
| File | Purpose | Dependencies | Exports |
|---|---|---|---|
base_channel.py |
Base Channel - Abstract base class for all channels | abc |
BaseChannel abstract class |
cli_channel.py |
CLI Channel - Publishes events to console/stdout | flexiai.channels.base_channel |
CLIChannel class |
quart_channel.py |
Quart Channel - Publishes events via SSE to web clients | flexiai.channels.base_channel, flexiai.core.events.sse_manager, quart |
QuartChannel class |
redis_channel.py |
Redis Channel - Publishes events to Redis Pub/Sub | flexiai.channels.base_channel, redis |
RedisChannel class |
channel_manager.py |
Channel Manager - Factory for creating active channels | flexiai.config.models, flexiai.channels.* |
get_active_channels() function |
multi_channel_publisher.py |
Multi-Channel Publisher - Publishes to multiple channels simultaneously | flexiai.channels.channel_manager |
MultiChannelPublisher class |
Relationships:
base_channel.py→ Base for all channel implementationscli_channel.py,quart_channel.py,redis_channel.py→ Inherit from base_channelchannel_manager.py→ Creates instances based on ACTIVE_CHANNELS configmulti_channel_publisher.py→ Uses channel_manager → Publishes to all active channels- All channels → Used by event_handler via multi_channel_publisher
| File | Purpose | Dependencies | Exports |
|---|---|---|---|
tools_manager.py |
Tools Manager - Core tool implementations (RAG, agent coordination, YouTube, CSV, Spreadsheet, Security) | flexiai.core.handlers.run_thread_manager, flexiai.toolsmith.tools_infrastructure.* |
ToolsManager class |
tools_registry.py |
Tools Registry - Maps tool names to callable functions | flexiai.toolsmith.tools_manager |
ToolsRegistry class |
Relationships:
tools_manager.py→ Uses all infrastructure modules → Provides tool implementationstools_registry.py→ Uses tools_manager → Maps tools for execution- Both → Used by controllers, tool_call_executor
| File | Purpose | Dependencies |
|---|---|---|
csv_entrypoint.py |
CSV Entry Point - Main CSV operations dispatcher | All CSV operation modules, utils, exceptions |
managers/csv_manager.py |
CSV Manager - Core CSV file operations | pandas, utils, exceptions |
operations/create_operations.py |
Create CSV files | csv_manager, utils |
operations/read_operations.py |
Read CSV data | csv_manager, utils |
operations/update_operations.py |
Update CSV rows | csv_manager, utils |
operations/delete_operations.py |
Delete CSV rows/files | csv_manager, utils |
operations/filter_operations.py |
Filter CSV rows | csv_manager, utils |
operations/data_validation_operations.py |
Validate CSV data | csv_manager, utils |
operations/data_transformation_operations.py |
Transform CSV data | csv_manager, utils |
utils/file_handler.py |
File path validation | exceptions |
utils/error_handler.py |
Error response formatting | exceptions |
utils/mixed_helpers.py |
Type conversion utilities | None |
exceptions/csv_exceptions.py |
CSV-specific exceptions | None |
Relationships:
csv_entrypoint.py→ Uses all operations → Used by tools_manager- Operations → Use csv_manager, utils, exceptions
- Utils → Used by operations and managers
| File | Purpose | Dependencies |
|---|---|---|
spreadsheet_entrypoint.py |
Spreadsheet Entry Point - Main spreadsheet operations dispatcher | All spreadsheet operation modules, utils, exceptions |
managers/spreadsheet_manager.py |
Spreadsheet Manager - Core spreadsheet operations | openpyxl, utils, exceptions |
operations/file_operations.py |
Create/open/close spreadsheets | spreadsheet_manager |
operations/sheet_operations.py |
Sheet management | spreadsheet_manager |
operations/data_entry_operations.py |
Write data to cells | spreadsheet_manager |
operations/data_retrieval_operations.py |
Read data from cells | spreadsheet_manager |
operations/data_analysis_operations.py |
Analyze spreadsheet data | spreadsheet_manager |
operations/formula_operations.py |
Formula management | spreadsheet_manager |
operations/formatting_operations.py |
Cell formatting | spreadsheet_manager |
operations/data_validation_operations.py |
Data validation | spreadsheet_manager |
operations/data_transformation_operations.py |
Data transformation | spreadsheet_manager |
operations/chart_operations.py |
Chart creation | spreadsheet_manager |
utils/file_handler.py |
File path validation | exceptions |
utils/error_handler.py |
Error response formatting | exceptions |
utils/mixed_helpers.py |
Type conversion utilities | None |
exceptions/spreadsheet_exceptions.py |
Spreadsheet-specific exceptions | None |
Relationships:
- Similar structure to CSV infrastructure
spreadsheet_entrypoint.py→ Uses all operations → Used by tools_manager- Operations → Use spreadsheet_manager, utils, exceptions
| File | Purpose | Dependencies |
|---|---|---|
csv_helpers.py |
CSV Helpers - Utility class for CSV operations (subscriber management) | pandas |
security_audit.py |
Security Audit - System security auditing tool | subprocess, os |
Relationships:
csv_helpers.py→ Used by tools_manager (for identify_subscriber, retrieve_billing_details, manage_services)security_audit.py→ Used by tools_manager (for security_audit tool)
| File | Purpose | Status |
|---|---|---|
_recycle/ocr_utils.py |
OCR Utilities - OCR for code editor screenshots | Experimental, not integrated |
_recycle/test_ocr.py |
OCR Testing - Test utilities for OCR | Experimental, not integrated |
Note: Files in _recycle/ folder are experimental and marked as "Coming Soon" in README.
| File | Purpose | Dependencies | Exports |
|---|---|---|---|
connection.py |
Database Connection - SQLAlchemy engine and session factory | sqlalchemy, os |
engine, SessionLocal, Base |
models.py |
Database Models - SQLAlchemy ORM models | sqlalchemy, flexiai.database.connection |
Model classes |
Relationships:
connection.py→ Sets up database → Used by modelsmodels.py→ Uses connection → Defines database schema- Currently minimal usage (prepared for future features)
| File | Purpose | Dependencies | Exports |
|---|---|---|---|
context_utils.py |
Context Utilities - Token counting and truncation | tiktoken, logging |
return_context() function |
Relationships:
- Used by:
tool_call_executor.py(to truncate tool outputs to fit token limits)
Key Functions:
return_context()- Truncates text to max_tokens, preserving end of text (most recent context)
This module contains experimental multi-agent system components. Files are organized into submodules:
core/- Base agent classes, factory, registrybehaviors/- Agent behaviors (adaptive, async, collaborative, learning)coordination/- Agent coordination (handoff, message broker, triage)memory/- Agent memory managementmonitoring/- Agent monitoring and safetyspecialists/- Specialized agent typesutils/- Agent utilitiesworkflows/- Workflow managementintegrations/- External integrations
Note: This module is experimental and not fully integrated into the main application flow.
Purpose: Web application entry point (Quart server)
Imports:
logging,uuid,os,csv(stdlib)quart(Quart, render_template, request, g, session, Response, redirect, url_for, jsonify)flexiai.config.models.GeneralSettingsflexiai.config.logging_config.setup_loggingflexiai.controllers.quart_chat_controller(as qcc)
Exports:
app(Quart instance)
Relationships:
- Uses:
GeneralSettings,setup_logging,quart_chat_controller - Used by: Hypercorn server, Docker
Key Functions:
initialize_controller()- Sets up QuartChatControllerload_user()- Manages user sessionhome()- Landing pagesubmit_user_info()- Form submission handler
Purpose: CLI application entry point
Imports:
logging,asyncio(stdlib)flexiai.config.models.GeneralSettingsflexiai.config.logging_config.setup_loggingflexiai.controllers.cli_chat_controller.CLIChatController
Exports:
main()async function
Relationships:
- Uses:
GeneralSettings,setup_logging,CLIChatController - Used by: Direct execution (
python chat.py)
Purpose: Pydantic settings models for all environment variables
Imports:
typing.Optionalpydantic_settings.BaseSettings, SettingsConfigDictpydantic.Field
Exports:
OpenAISettingsclassAzureOpenAISettingsclassDeepSeekSettingsclassQwenSettingsclassGitHubAzureInferenceSettingsclassGeneralSettingsclass
Relationships:
- Used by:
client_settings.py,channel_manager.py,controllers
Key Classes:
- Each Settings class defines environment variables for a provider
- All use
.envfile viaSettingsConfigDict(env_file=".env")
Purpose: Validates and loads provider-specific settings
Imports:
loggingpydantic.ValidationErrorflexiai.config.models.*(all Settings classes)
Exports:
configdict (validated settings)
Relationships:
- Uses:
models.*Settings - Used by:
credentials.py
Key Functions:
- Validates settings based on
CREDENTIAL_TYPE - Raises errors if required settings are missing
Purpose: Factory for creating singleton AI client
Imports:
logging,asyncio(stdlib)typing.Anyflexiai.credentials.credentials.get_client(as get_unified_client)
Exports:
get_client()- Synchronous client getterget_client_async()- Asynchronous client getter
Relationships:
- Uses:
credentials.get_client - Used by: All controllers (
cli_chat_controller,quart_chat_controller)
Key Functions:
get_client()- Returns cached client or creates new oneget_client_async()- Wraps get_client in executor for async contexts
Purpose: Configures application-wide logging
Imports:
os,logging(stdlib)logging.handlers.RotatingFileHandler
Exports:
setup_logging()function
Relationships:
- Used by:
app.py,chat.py
Key Functions:
setup_logging()- Configures file and console logging with rotation
Purpose: Unified credential manager for all AI providers
Imports:
logging,asyncio(stdlib)abc.ABC, abstractmethodtyping.Anyflexiai.config.client_settings.configopenai(OpenAI client)
Exports:
get_client()- Returns configured OpenAI-compatible client
Relationships:
- Uses:
client_settings.config - Used by:
client_factory.py
Key Functions:
- Creates OpenAI client with provider-specific configuration
- Supports: OpenAI, Azure, DeepSeek, Qwen, GitHub Azure Inference
Purpose: Manages CLI chat loop
Imports:
logging,asyncio(stdlib)logging.LoggerAdaptertyping.Anyflexiai.config.client_factory.get_client_asyncflexiai.core.handlers.run_thread_manager.RunThreadManagerflexiai.toolsmith.tools_manager.ToolsManagerflexiai.core.handlers.handler_factory.create_event_handlerflexiai.core.events.event_bus.global_event_busflexiai.channels.channel_manager.get_active_channelsflexiai.channels.multi_channel_publisher.MultiChannelPublisher
Exports:
CLIChatControllerclass
Relationships:
- Uses: All core handlers, tools_manager, channels, event_bus
- Used by:
chat.py
Key Methods:
create_async()- Factory methodrun_chat_loop()- Main chat loopprocess_user_message()- Handles user input
Purpose: Manages web chat via HTTP/SSE
Imports:
asyncio,json,threading,logging(stdlib)typing.Optionalquart(Blueprint, request, jsonify, render_template, Response, g)flexiai.config.models.GeneralSettingsflexiai.config.client_factory.get_client_asyncflexiai.core.handlers.run_thread_manager.RunThreadManagerflexiai.toolsmith.tools_manager.ToolsManagerflexiai.core.events.event_bus.global_event_busflexiai.core.events.sse_manager.SSEManagerflexiai.core.handlers.handler_factory.create_event_handler
Exports:
QuartChatControllerclasschat_bpBlueprintcontroller_instance(singleton)
Relationships:
- Uses: All core handlers, tools_manager, sse_manager, event_bus
- Used by:
app.py
Key Methods:
create_async()- Factory methodprocess_user_message()- Handles HTTP POSTstream_events()- SSE endpointrender_chat_page()- Chat UI route
Purpose: Manages OpenAI Assistant API threads, runs, and messages
Imports:
logging,asyncio(stdlib)typing.Any, Optional- OpenAI client
Exports:
RunThreadManagerclass
Relationships:
- Uses: OpenAI client
- Used by: All controllers, event_handler, tools_manager
Key Methods:
create_thread()- Creates new threadcreate_message()- Adds message to threadcreate_run()- Starts assistant runget_run_status()- Checks run statusget_messages()- Retrieves messagessubmit_tool_outputs()- Submits tool results
Purpose: Processes streaming events from AI service
Imports:
json,logging,asyncio(stdlib)typing.Any, Optional, Dict, Callableflexiai.core.handlers.tool_call_executor.ToolCallExecutorflexiai.core.handlers.run_thread_manager.RunThreadManagerflexiai.core.handlers.event_dispatcher.EventDispatcherflexiai.core.events.event_models.MessageDeltaEventflexiai.channels.multi_channel_publisher.MultiChannelPublisherflexiai.core.events.rolling_event_buffer.RollingEventBufferflexiai.core.events.session.ChatSessionflexiai.controllers.quart_chat_controller.QuartChatController(for type hints)
Exports:
EventHandlerclass
Relationships:
- Uses: tool_call_executor, run_thread_manager, event_dispatcher, channels, events, rolling_event_buffer, session
- Used by: Controllers (via handler_factory)
- Note: Imports QuartChatController for type hints only (circular dependency handled via TYPE_CHECKING)
Key Methods:
handle_streaming_events()- Main event processing loop_handle_message_delta()- Processes message deltas_handle_tool_call()- Handles tool calls_handle_run_complete()- Handles run completion
Purpose: Routes events to appropriate handlers
Imports:
loggingtyping.Any, Dict, Callableflexiai.core.events.event_models.*
Exports:
EventDispatcherclass
Relationships:
- Uses: event_models
- Used by: event_handler
Key Methods:
dispatch()- Routes event to handlerregister_handler()- Registers event handler- Maps event types to handler functions
Purpose: Creates EventHandler instances
Imports:
typing.Any, Dict, Callable, Optionalflexiai.core.handlers.event_handler.EventHandlerflexiai.core.handlers.run_thread_manager.RunThreadManagerflexiai.core.handlers.event_dispatcher.EventDispatcher
Exports:
create_event_handler()function
Relationships:
- Uses: event_handler, run_thread_manager, event_dispatcher
- Used by: Controllers
Key Functions:
create_event_handler()- Factory function that wires all dependencies
Purpose: Executes tool calls from AI assistant
Imports:
json,logging(stdlib)typing.Any, Dict, Callableflexiai.toolsmith.tools_registry.ToolsRegistryflexiai.utils.context_utils.return_context
Exports:
ToolCallExecutorclass
Relationships:
- Uses: tools_registry, context_utils
- Used by: event_handler
Key Methods:
execute()- Executes a tool call_execute_tool()- Internal tool execution- Uses
return_context()to truncate tool outputs to fit token limits
Purpose: Pydantic models for all event types
Imports:
pydantic.BaseModel, Fieldtyping.Any, Dict, Listtime(stdlib)
Exports:
- Event model classes (MessageDeltaEvent, ThreadRunEvent, etc.)
Relationships:
- Used by: All event-related modules
Key Classes:
MessageDeltaEvent- Message delta updatesThreadRunEvent- Thread run statusToolCallEvent- Tool call requests- Other event types
Purpose: Pub/sub system for events (singleton)
Imports:
loggingtyping.Any, Callable, Dict, List
Exports:
global_event_businstanceEventBusclass
Relationships:
- Used by: Controllers, event_handler, channels
Key Methods:
subscribe()- Subscribe to event typepublish()- Publish eventunsubscribe()- Unsubscribe from event type
Purpose: Manages Server-Sent Events for web clients
Imports:
collections.defaultdict, dequethreadinglogging
Exports:
SSEManagerclassglobal_sse_managerinstance
Relationships:
- Used by: quart_channel, quart_chat_controller
Key Methods:
register_client()- Register SSE clientsend_event()- Send event to clientunregister_client()- Remove client
Purpose: Manages chat session state
Imports:
threading,asyncio(stdlib)flexiai.core.events.rolling_event_buffer.RollingEventBuffer
Exports:
ChatSessionclass
Relationships:
- Uses: rolling_event_buffer
- Used by: event_handler
Key Methods:
- Manages session state and event history
Purpose: Maintains rolling buffer of recent events
Imports:
loggingcollections.OrderedDicttyping.Dict, List
Exports:
RollingEventBufferclass
Relationships:
- Used by: session
Key Methods:
add()- Add event to bufferget_recent()- Get recent events- Maintains fixed-size buffer
Purpose: Abstract base class for all channels
Imports:
abc.ABC, abstractmethodtyping.Any
Exports:
BaseChannelabstract class
Relationships:
- Base for: cli_channel, quart_channel, redis_channel
Key Methods:
publish_event()- Abstract method to be implemented
Purpose: Publishes events to console
Imports:
loggingtyping.Anyflexiai.channels.base_channel.BaseChannel
Exports:
CLIChannelclass
Relationships:
- Uses: base_channel
- Used by: channel_manager, multi_channel_publisher
Key Methods:
publish_event()- Prints events to stdout
Purpose: Publishes events via SSE to web clients
Imports:
logging,json(stdlib)typing.Anypydantic.BaseModelquart(g, has_request_context)flexiai.channels.base_channel.BaseChannelflexiai.core.events.sse_manager.global_sse_manager
Exports:
QuartChannelclass
Relationships:
- Uses: base_channel, sse_manager
- Used by: channel_manager, multi_channel_publisher
Key Methods:
publish_event()- Sends events via SSE
Purpose: Publishes events to Redis Pub/Sub
Imports:
logging,json(stdlib)typing.Anyredisflexiai.channels.base_channel.BaseChannel
Exports:
RedisChannelclass
Relationships:
- Uses: base_channel, redis
- Used by: channel_manager, multi_channel_publisher
Key Methods:
publish_event()- Publishes to Redis channel
Purpose: Factory for creating active channels
Imports:
loggingflexiai.config.models.GeneralSettingsflexiai.channels.cli_channel.CLIChannelflexiai.channels.redis_channel.RedisChannelflexiai.channels.quart_channel.QuartChannel
Exports:
get_active_channels()function
Relationships:
- Uses: GeneralSettings, all channel classes
- Used by: multi_channel_publisher, controllers
Key Functions:
get_active_channels()- Returns list of active channels based on ACTIVE_CHANNELS config
Purpose: Publishes to multiple channels simultaneously
Imports:
loggingtyping.Anyflexiai.channels.channel_manager.get_active_channels
Exports:
MultiChannelPublisherclass
Relationships:
- Uses: channel_manager
- Used by: event_handler
Key Methods:
publish()- Publishes to all active channels
Purpose: Core tool implementations
Imports:
logging,threading,subprocess,os,urllib,json(stdlib)typing.Any, Dict, Tuple, List, Optional, Union, TYPE_CHECKINGdotenv.load_dotenvgoogleapiclient.discovery.buildgoogleapiclient.errors.HttpErrorflexiai.core.handlers.run_thread_manager.RunThreadManagerflexiai.toolsmith.tools_infrastructure.csv_helpers.CSVHelpersflexiai.toolsmith.tools_infrastructure.spreadsheet_infrastructure.*flexiai.toolsmith.tools_infrastructure.csv_infrastructure.csv_entrypoint.csv_entrypointflexiai.toolsmith.tools_infrastructure.security_audit.SecurityAudit
Exports:
ToolsManagerclass
Relationships:
- Uses: run_thread_manager, all infrastructure modules
- Used by: tools_registry, controllers
Key Methods:
save_processed_content()- RAG storageload_processed_content()- RAG retrievalinitialize_agent()- Agent coordinationcommunicate_with_assistant()- Inter-agent communicationsearch_youtube()- YouTube searchsearch_on_youtube()- YouTube search with embedscsv_operations()- CSV operations dispatcherfile_operations()- Spreadsheet file operationssecurity_audit()- Security auditing- Many more tool methods...
Purpose: Maps tool names to callable functions
Imports:
loggingtyping.Any, Callable, Dictflexiai.toolsmith.tools_manager.ToolsManager
Exports:
ToolsRegistryclassRegistryErrorexception
Relationships:
- Uses: tools_manager
- Used by: tool_call_executor
Key Methods:
map_core_tools()- Registers core toolsmap_custom_tools()- Registers custom toolsget_tool()- Retrieves tool by nameget_all_tools()- Returns all registered tools
Purpose: Main CSV operations dispatcher
Imports:
- All CSV operation modules
- All CSV utils
- CSV exceptions
Exports:
csv_entrypoint()function
Relationships:
- Uses: All CSV operations, utils, exceptions
- Used by: tools_manager
Key Functions:
csv_entrypoint()- Routes CSV operations to appropriate handlers
Purpose: Main spreadsheet operations dispatcher
Imports:
- All spreadsheet operation modules
- All spreadsheet utils
- Spreadsheet exceptions
Exports:
- Multiple operation functions (file_operations, sheet_operations, etc.)
Relationships:
- Uses: All spreadsheet operations, utils, exceptions
- Used by: tools_manager
Purpose: Utility class for CSV operations (used by tools_manager for subscriber management)
Imports:
os,pandas,logging(stdlib)
Exports:
CSVHelpersclass
Relationships:
- Used by:
tools_manager.py(for identify_subscriber, retrieve_billing_details, manage_services)
Key Methods:
handle_csv()- Dispatcher for CSV operations (read/write/update)clean_dataframe()- Cleans DataFrame (strip, lowercase)find_matching_records()- Finds records matching search criteria
Purpose: System security auditing tool
Imports:
subprocess,os,logging(stdlib)- Other security-related imports
Exports:
SecurityAuditclasssecurity_audit_dispatcher()function
Relationships:
- Used by:
tools_manager.py(for security_audit tool)
Files:
ocr_utils.py- OCR utilities for code editor screenshots (optimized pipeline)test_ocr.py- OCR testing utilities
Purpose: OCR functionality (marked as "Coming Soon" in README)
Note: Files in _recycle/ folder are experimental/in development and not fully integrated.
Relationships:
- Not currently used by main application
- Prepared for future OCR tool integration
Purpose: Database connection setup
Imports:
os(stdlib)sqlalchemy(create_engine, sessionmaker, declarative_base)
Exports:
engine- SQLAlchemy engineSessionLocal- Session factoryBase- Declarative base
Relationships:
- Used by: models
Purpose: Database ORM models
Imports:
datetime(stdlib)sqlalchemy(Column, Integer, String, DateTime, Text, ForeignKey, relationship)flexiai.database.connection.Base
Exports:
- Model classes
Relationships:
- Uses: connection.Base
- Currently minimal usage
Purpose: Context management utilities - Token counting and truncation
Imports:
loggingtiktoken
Exports:
return_context()function - Truncates text to fit token limits
Relationships:
- Used by:
tool_call_executor.py(to truncate tool outputs)
Key Functions:
return_context(text, max_tokens, model)- Truncates text to max_tokens for specified model- Uses tiktoken for accurate token counting
- Preserves end of text when truncating (keeps most recent context)
Entry Points (app.py, chat.py)
↓
Controllers (CLIChatController, QuartChatController)
↓
Client Factory → Credentials → Client Settings → Models
↓
Run Thread Manager → OpenAI Client
↓
Tools Manager → Tools Registry
↓
Event Handler → Event Dispatcher → Tool Call Executor
↓
Multi-Channel Publisher → Channels (CLI/Quart/Redis)
↓
Event Bus → Event Models
models.py
↓
client_settings.py
↓
credentials.py
↓
client_factory.py
↓
controllers
controllers
↓
handler_factory.py
↓
event_handler.py
├→ event_dispatcher.py
├→ tool_call_executor.py
│ ↓
│ tools_registry.py
│ ↓
│ tools_manager.py
│ ↓
│ infrastructure modules
└→ multi_channel_publisher.py
↓
channels (CLI/Quart/Redis)
↓
event_bus.py
↓
event_models.py
AI Assistant (via OpenAI API)
↓
tool_call_executor.py
↓
tools_registry.py
↓
tools_manager.py
├→ CSV Infrastructure
├→ Spreadsheet Infrastructure
├→ Security Audit
└→ Core Tools (RAG, Agent Coordination, YouTube)
CLI (chat.py):
chat.py
→ setup_logging()
→ GeneralSettings()
→ CLIChatController.create_async()
→ get_client_async()
→ credentials.get_client()
→ client_settings.config
→ models.*Settings
→ RunThreadManager(client)
→ ToolsManager(client, run_thread_manager)
→ ToolsRegistry(tools_manager)
→ create_event_handler()
→ EventHandler(...)
→ EventDispatcher()
→ ToolCallExecutor(tools_registry)
→ get_active_channels()
→ CLIChannel()
→ run_chat_loop()
Web (app.py):
app.py
→ setup_logging()
→ GeneralSettings()
→ Quart(app)
→ register_blueprint(quart_chat_controller.chat_bp)
→ @before_serving
→ QuartChatController.create_async()
(similar to CLI initialization)
→ app.run()
CLI:
User Input
→ CLIChatController.process_user_message()
→ RunThreadManager.create_message()
→ RunThreadManager.create_run()
→ EventHandler.handle_streaming_events()
→ For each event:
→ EventDispatcher.dispatch()
→ ToolCallExecutor.execute() (if tool call)
→ MultiChannelPublisher.publish()
→ CLIChannel.publish_event()
→ Print to console
Web:
HTTP POST /chat/message
→ QuartChatController.process_user_message()
→ Similar to CLI flow
→ QuartChannel.publish_event()
→ SSEManager.send_event()
→ SSE stream to browser
AI Assistant requests tool
→ EventHandler receives tool_call event
→ ToolCallExecutor.execute()
→ ToolsRegistry.get_tool()
→ ToolsManager method
→ Infrastructure module (CSV/Spreadsheet/etc.)
→ Returns result
→ RunThreadManager.submit_tool_outputs()
→ AI Assistant receives result
→ Continues conversation
flexiai.core.handlers.run_thread_manager- Used by controllers, tools_manager, event_handlerflexiai.toolsmith.tools_manager- Used by controllers, tools_registryflexiai.config.models- Used by most modulesflexiai.core.events.event_bus- Used by controllers, event_handler, channelsflexiai.channels.channel_manager- Used by controllers, multi_channel_publisher
openai- AI clientquart- Web frameworkpandas- CSV operationsopenpyxl- Spreadsheet operationsredis- Redis channelpydantic- Settings and modelssqlalchemy- Database
- Configuration:
models.py→client_settings.py→credentials.py→client_factory.py - Controllers: Both use
client_factory,run_thread_manager,tools_manager,event_handler - Event System:
event_handler→event_dispatcher→tool_call_executor→tools_registry - Channels:
multi_channel_publisher→channel_manager→ individual channels →event_bus - Tools:
tools_manager→ infrastructure modules (CSV, Spreadsheet, Security) → operations → managers → utils - Thread Management:
run_thread_manager→ OpenAI Assistant API → threads/runs/messages
base.html- Base templateindex.html- Landing pagechat.html- Chat interface page_chat_widget.html- Chat widget component_navbar.html- Navigation bar component
Relationships:
- Used by:
app.py,quart_chat_controller.py(viarender_template())
css/- Stylesheetsjs/- JavaScript filesimages/- Image assets
Relationships:
- Served by:
app.py(via Quart static file serving) - Referenced by: HTML templates
.env- Environment variables (git-ignored).env.template- Environment templaterequirements.txt- Python dependenciesrequirements.in- Source dependenciesenvironment.yml- Conda environmentDockerfile- Docker configuration
README.md- Main documentation (root)docs/ARCHITECTURE.md- System architecture and designdocs/WORKFLOW.md- Execution workflows and data flowdocs/TOOLING.md- Tool capabilities and usagedocs/ENV_SETUP.md- Environment setup guidedocs/FILE_MAPPING.md- This file (detailed internal reference)
- Total Python Files: 113
- Core Application: ~30 files
- Tool Infrastructure: ~50 files
- Agents (Experimental): ~30 files
- Configuration: 4 files
- Controllers: 2 files
- Channels: 6 files
- Core Handlers: 5 files
- Core Events: 5 files
- Templates: 5 HTML files
- Static Assets: Multiple CSS/JS/image files
This comprehensive mapping provides detailed information about every file in the codebase, including exact imports, exports, relationships, and data flow patterns. Use it to understand how components interact and where to make changes.