Skip to main content

Kotemari: A Python library and CLI tool to analyze codebases, understand dependencies, and generate accurate context for LLMs. Simplifies RAG generation for coding tasks.

Project description

Kotemari 🪄

PyPI version Build Status Code Coverage License: MIT

Kotemari is a Python library designed to analyze your Python project structure, understand dependencies, and intelligently generate context for Large Language Models (LLMs) like GPT. 🧠 Its core purpose is to be integrated into other development tools (like IDE extensions, analysis scripts, or chat interfaces) to provide on-demand project insights and context. It also features real-time file monitoring to keep the analysis up-to-date effortlessly! ✨

🤔 Why Kotemari?

Integrating project understanding capabilities into tools or automating context generation for LLMs can be complex. Kotemari simplifies this by providing a robust Python API that:

  • 🎯 Delivers Smart Context: Generate concise context strings including only necessary files and their dependencies via simple API calls.
  • 🔄 Stays Up-to-Date: Offers background file monitoring and automatic cache/dependency updates, ensuring the information provided by the API is current.
  • 🔍 Provides Deep Insight: Exposes methods to access detailed dependency information (direct and reverse) derived from analyzing Python import statements.
  • ⚙️ Offers Flexibility: Easily configurable through Python arguments or an optional .kotemari.yml file, respecting .gitignore rules.
  • 🧩 Enables Integration: Designed to be easily embedded into your custom Python applications and development workflows.

Kotemari empowers your tools by providing sophisticated project analysis capabilities through a simple and effective Python API. 🎉

🚀 Installation

Kotemari is currently under development. To install the development version:

  1. Clone the repository:
    git clone https://github.com/<YOUR_GITHUB_USERNAME>/kotemari.git
    cd kotemari
    
  2. Create a virtual environment:
    # Using venv
    python -m venv .venv
    source .venv/bin/activate # On Windows use `.venv\Scripts\activate`
    
    # Or using uv (recommended)
    uv venv
    source .venv/bin/activate # On Windows use `.venv\Scripts\activate`
    
  3. Install the package in editable mode:
    # Using pip
    pip install -e .[dev]
    
    # Or using uv
    uv pip install -e .[dev]
    

(Once released, installation will be as simple as pip install kotemari)

✨ Usage (Python API)

Using Kotemari in your Python code is straightforward:

import logging
from pathlib import Path
from kotemari import Kotemari

# Optional: Configure logging to see Kotemari's internal activity
logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(name)s: %(message)s')

# 1. Initialize Kotemari with your project's root directory
project_path = Path("./your/project/path") # <-- Change this!
kotemari = Kotemari(project_path)

# 2. Analyze the project (builds initial cache and dependency graph)
print("Analyzing project...")
kotemari.analyze_project()
print("Analysis complete!")

# 3. Get a list of analyzed files (FileInfo objects)
print("\nAnalyzed Files:")
all_files = kotemari.list_files()
for file_info in all_files[:5]: # Print first 5 for brevity
    print(f"- {file_info.path.relative_to(project_path)} (Hash: {file_info.hash[:7]}...)")

# 4. Get dependencies of a specific file
target_file = project_path / "src/module_a.py" # Example
print(f"\nDependencies of {target_file.name}:")
try:
    dependencies = kotemari.get_dependencies(target_file)
    if dependencies:
        for dep_path in dependencies:
            print(f"- {dep_path.relative_to(project_path)}")
    else:
        print("- No direct dependencies found.")
except FileNotFoundError:
    print(f"- File {target_file.name} not found in analysis results.")

# 5. Get files that depend ON a specific file (reverse dependencies)
dependent_on_file = project_path / "src/utils.py" # Example
print(f"\nFiles depending on {dependent_on_file.name}:")
try:
    reverse_deps = kotemari.get_reverse_dependencies(dependent_on_file)
    if reverse_deps:
        for rev_dep_path in reverse_deps:
            print(f"- {rev_dep_path.relative_to(project_path)}")
    else:
        print("- No files directly depend on this.")
except FileNotFoundError:
    print(f"- File {dependent_on_file.name} not found in analysis results.")

# 6. Generate formatted context for LLM (target file + dependencies)
context_file = project_path / "src/main_logic.py" # Example
print(f"\nGenerating context for {context_file.name}:")
try:
    context_string = kotemari.get_context(context_file)
    print("--- Context Start ---")
    print(context_string[:500] + "... (truncated)") # Print start for brevity
    print("--- Context End ---")
except FileNotFoundError:
    print(f"- File {context_file.name} not found.")
except Exception as e:
    print(f"An error occurred: {e}")

# 7. Optional: Start background file watching for real-time updates
# Kotemari will automatically update its internal state when files change.
print("\nStarting file watcher (runs in background)...")
kotemari.start_watching() 

# --- Your application logic here --- 
# You can now query kotemari methods (list_files, get_dependencies, etc.) 
# and get up-to-date results reflecting any file changes.

print("Watcher is running. Modify project files to see updates (check logs if INFO enabled).")
input("Press Enter to stop watching and exit...\n")

print("Stopping watcher...")
kotemari.stop_watching()
print("Watcher stopped.")

Key API Methods:

  • Kotemari(project_root, config_path=None, use_cache=True, log_level=logging.WARNING): Initialize the analyzer.
  • analyze_project(): Performs the initial full analysis.
  • list_files(): Returns List[FileInfo] for all tracked files.
  • get_dependencies(file_path: Path): Returns Set[Path] of files the target file imports.
  • get_reverse_dependencies(file_path: Path): Returns Set[Path] of files that import the target file.
  • get_context(file_path: Path, include_dependencies=True, formatter=...): Generates a context string.
  • start_watching() / stop_watching(): Controls the background file monitor.
  • clear_cache(): Removes cached analysis results.

🛠️ CLI Usage (Optional)

Kotemari also provides a basic command-line interface for quick checks and simple tasks:

# Activate environment
source .venv/bin/activate # Or .venv\Scripts\activate

# Basic commands
kotemari analyze
kotemari list
kotemari tree
kotemari dependencies <path/to/file.py>
kotemari context <path/to/file1.py> [<path/to/file2.py>...]

# Get help
kotemari --help
kotemari analyze --help

🔧 Development

Interested in contributing?

  1. Set up the environment (See Installation section).
  2. Run tests:
    pytest
    
  3. Check code coverage:
    pytest --cov=src/kotemari
    

Please refer to CONTRIBUTING.md (to be created) for contribution guidelines.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

💻 Supported Environments

  • Python: 3.8+
  • OS: Windows, macOS, Linux (tested primarily on Windows)

Let Kotemari simplify your Python project analysis! 🌳

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

kotemari-0.1.0.tar.gz (165.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kotemari-0.1.0-py3-none-any.whl (69.4 kB view details)

Uploaded Python 3

File details

Details for the file kotemari-0.1.0.tar.gz.

File metadata

  • Download URL: kotemari-0.1.0.tar.gz
  • Upload date:
  • Size: 165.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.5

File hashes

Hashes for kotemari-0.1.0.tar.gz
Algorithm Hash digest
SHA256 18be166d807e0a7a22b1d92f7e5e22a6820c104b1f87a35239d6e482db3a52ef
MD5 fddf37c30db9bc200530a82f8278ca28
BLAKE2b-256 c0e16e1d28f94ac75cd92b1a77ec1f1ab5fcf2cbcf70e2af1dfadaf0a7b8bd53

See more details on using hashes here.

File details

Details for the file kotemari-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: kotemari-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 69.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.5

File hashes

Hashes for kotemari-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 43aee2f0d0fb575669a36bcde4e8e9e774dd2d8396605c9b91e7ec01cfd10668
MD5 d26967eae79d63dc4b5d8c4d50c7a8e6
BLAKE2b-256 235d9727e77c703baf41724f9cdd395edd55ed9b5daa02596f729b2a9b5ca81c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page