Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

16 Commits

Folders and files

Repository files navigation

LLM Chat Tool with Markdown Editing

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.

Features

  • 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: --verbose prints 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

Setup

1. Install Dependencies

pip install -r requirements.txt

2. Configure API Keys

Create 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_here

You 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.8

Security Note: Keep your .env file out of version control. Add it to .gitignore.

3. Create Markdown Directory

The tool will automatically create a markdown_files directory in the current location where markdown files will be stored and managed.

Usage

Basic Usage

# 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

Command Line Options

  • -p, --provider: Choose LLM provider (openai or openrouter, default: openai)
  • -m, --model: Specify model name (defaults: gpt-5-mini for OpenAI, xai/grok-1.5-mini for 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

Runtime Slash Commands

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

Verbose Trace Output

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)

Available Tools

The chat interface provides these markdown file operations:

  1. List Files: list_markdown_files(path?) – Show .md files (use sparingly)
  2. Read File: read_markdown_file(file_path) – Display file contents
  3. Edit Section: edit_markdown_section(filename, section_header, new_content, insert_mode) – Edit section BODY (not header)
  4. Validate File: validate_markdown_file(filename) – Check structure and report issues
  5. Normalize File: normalize_markdown_file(filename, header_text?) – Merge duplicate same-named headers
  6. Table Operations (CRITICAL): edit_table(filename, section_header, table_content, operation) – Create/replace/append/prepend rows in tables
  7. Links: add_link, list_links, edit_link, delete_link
  8. AST Tools: parse_markdown_ast, edit_section_advanced, list_sections_detailed, move_section, add_list_items, apply_text_formatting, normalize_file_advanced, validate_advanced
  9. File System: create_file, create_folder, move_file, delete_file, delete_folder, merge_files, show_tree

Table Operations — CRITICAL

  • Always use edit_table for any table creation/modification/row updates.
  • Do not use edit_markdown_section for table content.
  • Operations: replace (entire table), append_rows, prepend_rows.

Ambiguity Handling

  • 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.

Safety & Scope

  • Operate strictly within the configured {markdown_root}.
  • Destructive actions (delete, overwrite) require clear intent; confirm when ambiguous.
  • The conversation.log file is output-only and is never written to by tools.

Example Conversations

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.

Token Counting

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.

Context Size Management

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.

Extensibility

Adding new tools or LLM providers is straightforward:

  • Tools: Add a function to MarkdownTools or another class, then register it in self.tool_registry with a JSON schema.
  • Providers: Implement a new _call_<provider>_api method and extend LLMProvider.

Testing

The tool includes comprehensive testing functionality for both manual verification and automated testing.

Automated Test Suite

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-4

The test suite will:

  1. Create a temporary markdown_test directory
  2. Run basic functionality tests (create, read, list files)
  3. Test advanced markdown operations (sections, validation)
  4. Test error handling and edge cases
  5. Clean up the test environment
  6. Provide detailed results summary

Complete Test Environment

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-check

The test runner automatically:

  • ✅ Checks virtual environment status
  • ✅ Validates required dependencies
  • ✅ Verifies API key configuration
  • ✅ Provides helpful error messages and setup guidance

Live Network Tests (Token Consuming)

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.py

When 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.py

Programmatic Interface

Use 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)

Disclaimer

This tool is for educational purposes only. It prioritizes readability over production-level robustness. Use it to learn, experiment, and extend!

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages