A minimal, modular Python CLI tool for experimenting with LLM interactions and markdown file operations. Designed for learning and experimentation with function calling, tool registration patterns, and clean API abstraction.
- Multi-Provider Support: Works with OpenAI and OpenRouter APIs
- Function Calling: Dynamic tool registration with automatic JSON schema generation
- Markdown Operations: List, read, edit sections, and validate markdown files
- AST-Aware Editing: Advanced section/list/link manipulation via Marko AST tools
- Rich CLI Interface: Progress bars, colored output, and real-time token counting
- Verbose Runtime Trace:
--verboseprints local steps, LLM calls, retries, and tool execution - Modular Architecture: Clean separation between prompt construction and API calls
- Error Handling: Graceful degradation with clear user feedback
- Slash Commands:
/help,/reset,/stats,/provider - Auto Compaction: Long conversations are compacted to keep prompts manageable
- Environment Management: Secure API key handling with .env file support
- Configurable Root Directory: Use custom directories for markdown files
- Programmatic Interface: Use the chat tool in scripts and tests
- Automated Testing: Comprehensive test suite for all functionality
pip install -r requirements.txtCreate a .env file in the same directory as chat_tool.py:
# For OpenAI
OPENAI_API_KEY=your_openai_api_key_here
# For OpenRouter
OPENROUTER_API_KEY=your_openrouter_api_key_hereYou need at least one key configured: OPENAI_API_KEY or OPENROUTER_API_KEY.
Optional runtime tuning:
COMPACT_TRIGGER_TOKENS=8000
COMPACT_KEEP_MESSAGES=16
LLM_MAX_RETRIES=2
LLM_RETRY_BASE_DELAY_S=0.8Security Note: Keep your .env file out of version control. Add it to .gitignore.
The tool will automatically create a markdown_files directory in the current location where markdown files will be stored and managed.
# Use OpenAI GPT-3.5-turbo (default)
python chat_tool.py
# Use OpenAI GPT-4
python chat_tool.py --provider openai --model gpt-4
# Use OpenRouter
python chat_tool.py --provider openrouter --model xai/grok-1.5-mini
# Enable verbose mode for learning/debugging
python chat_tool.py --verbose
# Use custom directory for markdown files
python chat_tool.py --root my_custom_directory
# Combine options
python chat_tool.py --provider openai --model gpt-4 --root project_docs --verbose-p, --provider: Choose LLM provider (openaioropenrouter, default:openai)-m, --model: Specify model name (defaults:gpt-5-minifor OpenAI,xai/grok-1.5-minifor OpenRouter)-v, --verbose: Enable detailed operation output for learning purposes-r, --root: Root directory for markdown files (default:markdown_files)-h, --help: Show help message and examples
Inside the interactive session:
/help: Show help text and examples/reset: Clear conversation history/stats: Show provider/model, token estimate, and runtime counters/provider: Show current provider/model/provider openai [model]: Switch provider/model in-session/provider openrouter [model]: Switch provider/model in-session
Run with --verbose to print [TRACE ...] lines showing:
- local deterministic actions (for example direct read/create/list)
- LLM invocation start/completion and retry/backoff
- tool invocations requested by the LLM
- local post-LLM operations (output post-processing and index refresh)
The chat interface provides these markdown file operations:
- List Files:
list_markdown_files(path?)– Show .md files (use sparingly) - Read File:
read_markdown_file(file_path)– Display file contents - Edit Section:
edit_markdown_section(filename, section_header, new_content, insert_mode)– Edit section BODY (not header) - Validate File:
validate_markdown_file(filename)– Check structure and report issues - Normalize File:
normalize_markdown_file(filename, header_text?)– Merge duplicate same-named headers - Table Operations (CRITICAL):
edit_table(filename, section_header, table_content, operation)– Create/replace/append/prepend rows in tables - Links:
add_link,list_links,edit_link,delete_link - AST Tools:
parse_markdown_ast,edit_section_advanced,list_sections_detailed,move_section,add_list_items,apply_text_formatting,normalize_file_advanced,validate_advanced - File System:
create_file,create_folder,move_file,delete_file,delete_folder,merge_files,show_tree
- Always use
edit_tablefor any table creation/modification/row updates. - Do not use
edit_markdown_sectionfor table content. - Operations:
replace(entire table),append_rows,prepend_rows.
- When users refer to partial names (e.g., “projects”), disambiguate first if multiple matches exist.
- Proceed without asking only when there is exactly one clear match or recent context makes it unambiguous.
- Operate strictly within the configured
{markdown_root}. - Destructive actions (delete, overwrite) require clear intent; confirm when ambiguous.
- The
conversation.logfile is output-only and is never written to by tools.
You (127 tokens): List all my markdown files
Assistant: Sure! Here are the files ...
You (142 tokens): Edit section "Changelog" in project.md with content "- Added new feature X"
Assistant: Successfully updated section 'Changelog' in project.md
You (98 tokens): Validate project.md
Assistant: File is valid. 7 headers, 523 words.
The tool shows an approximate token count next to your prompt so you know how large the current context is. OpenAI models use tiktoken for accuracy.
As chats grow, prompts become larger and slower. The tool now includes automatic local history compaction (no extra LLM call) when prompt size crosses COMPACT_TRIGGER_TOKENS.
Adding new tools or LLM providers is straightforward:
- Tools: Add a function to
MarkdownToolsor another class, then register it inself.tool_registrywith a JSON schema. - Providers: Implement a new
_call_<provider>_apimethod and extendLLMProvider.
The tool includes comprehensive testing functionality for both manual verification and automated testing.
Run the full test suite to verify all functionality:
# Run with default settings (OpenAI)
python test_chat_tool.py
# Run with OpenRouter
python test_chat_tool.py --provider openrouter
# Run with specific model
python test_chat_tool.py --provider openai --model gpt-4The test suite will:
- Create a temporary
markdown_testdirectory - Run basic functionality tests (create, read, list files)
- Test advanced markdown operations (sections, validation)
- Test error handling and edge cases
- Clean up the test environment
- Provide detailed results summary
The test script includes comprehensive environment validation:
# Run with full environment checks and validation
python test_chat_tool.py
# Skip API key checks (for testing setup without API access)
python test_chat_tool.py --skip-api-checkThe test runner automatically:
- ✅ Checks virtual environment status
- ✅ Validates required dependencies
- ✅ Verifies API key configuration
- ✅ Provides helpful error messages and setup guidance
There is a dedicated live test module that calls real provider APIs and consumes tokens/credits:
/Users/gabriel/work/elks_chat/tests/test_live_network_token_consuming_providers.py
It is opt-in and skipped by default.
Required setup:
RUN_LIVE_NETWORK_TESTS=1(to enable execution)OPENAI_API_KEY(for OpenAI live test)OPENROUTER_API_KEY(for OpenRouter live test)
Optional model overrides:
OPENAI_MODEL(default:gpt-5-mini)OPENROUTER_MODEL(default:xai/grok-1.5-mini)
Run:
RUN_LIVE_NETWORK_TESTS=1 \
/Users/gabriel/work/elks_chat/venv/bin/python -m unittest \
/Users/gabriel/work/elks_chat/tests/test_live_network_token_consuming_providers.pyWhen enabled, tests will prompt once with:
LIVE network tests consume tokens/credits. Press ENTER to continue:
To bypass the prompt in automation:
RUN_LIVE_NETWORK_TESTS=1 LIVE_NETWORK_TESTS_NO_PROMPT=1 \
/Users/gabriel/work/elks_chat/venv/bin/python -m unittest \
/Users/gabriel/work/elks_chat/tests/test_live_network_token_consuming_providers.pyUse the chat tool in your own scripts:
from chat_tool import LLMChatTool, LLMProvider
# Initialize with custom directory
chat = LLMChatTool(
provider=LLMProvider.OPENAI,
model="gpt-3.5-turbo",
markdown_root="my_custom_dir"
)
# Process messages programmatically
response = chat.process_message("create a test.md file")
print(response)This tool is for educational purposes only. It prioritizes readability over production-level robustness. Use it to learn, experiment, and extend!