Skip to content

swapniel99/leetcode_tutor

Repository files navigation

LeetCode Tutor

AI-powered LeetCode tutoring bot. Helps users solve coding problems step-by-step with code testing, progress tracking, and concept explanations.

Features

  • Problem Fetching — Input any LeetCode/HackerRank/coding problem URL
  • Code Testing — Run and test solutions with edge cases
  • Progress Tracking — Persistent memory of problems worked on and solution attempts
  • Guided Learning — Tutor guides toward solutions rather than giving answers
  • Concept Explanation — Search and explain algorithms and data structures
  • Complexity Analysis — Help optimize time/space complexity

Quick Start

# Install dependencies
uv sync

# Run the bot UI
uv run python gradio_test.py

Opens web UI at http://localhost:7860

Usage Examples

Give problem URL:

User: Help with https://leetcode.com/problems/two-sum/
Bot: [fetches problem] Here's Two Sum... what approach are you thinking?

Text problem name:

User: I want to solve LeetCode Two Sum problem
Bot: [searches for link, fetches problem] Here's Two Sum...

Test your solution:

User: Here's my solution:
def twoSum(nums, target):
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]

Bot: [tests with multiple cases, finds edge cases] Works but O(n²). Try hash map approach...

View progress:

User: What problems have I solved?
Bot: [shows list from memory] You've worked on: Two Sum, Best Time to Buy Stock, Palindrome...

Configuration

Model selection (assistant/config.py):

generation_config = {
    'platform': 'openai',  # 'openai', 'azure', 'openrouter'
    'model': 'gpt-4o-mini',
    'temperature': 0.7
}

Credentials (at project root):

  • .openai.envOPENAI_API_KEY
  • .azure.openai.env — Azure OpenAI credentials
  • .openrouter.env — OpenRouter API key

Architecture

gradio_test.py → pandora_bot.py → ChatBot instance
                    ↓
        ┌───────────┼──────────┐
        ↓           ↓          ↓
    chat_generator  prompt_builder  tools_list
    (LLM backend)   (LeetCode tutor) (8 tools)

Key Components:

  • ChatBot (chatbot_factory.py) — Agentic loop: generate → tool calls → feedback → repeat
  • Prompt (prompts/pandora_prompt.txt) — Tutor behavior and tool usage instructions
  • Tools (tools/pandora_functions.py) — 8 functions for fetching, testing, searching, memory
  • Storage (utils/LocalStorageDB) — Persistent KV store for problem/solution history

Tools

Tool Purpose When Used
fetch_problem Extract problem from URL User provides problem link or bot finds via web_search
evaluate_python_code Run code with test cases User shares solution code; bot tests with basic + edge cases
save_to_memory Store problems/solutions After fetching problem; after evaluating solution
get_from_memory Retrieve past attempts User asks about previous work on same problem
list_memory_keys Show progress history User asks "what problems have I solved?"
forget_from_memory Delete specific entry User wants to clear old attempts/notes
clear_memory Clear by pattern User restarts or clears all solution attempts
web_search Find resources User names problem without URL; bot searches for link or concept explanation

Workflow

  1. User mentions problem → fetch via URL or web search
  2. Bot fetches problem → extract title, description, constraints
  3. Bot saves to memoryproblem_id, problem details
  4. User shares codebot runs evaluate_python_code immediately
    • Tests with basic test cases (from problem examples)
    • Tests edge cases (empty input, single element, boundary values)
    • Shows any runtime errors or incorrect output
  5. Bot suggests improvements → complexity analysis, optimizations, bug fixes
  6. History trackinglist_memory_keys shows progress

Code Evaluation Flow

When user shares code:

# User gives:
def twoSum(nums, target):
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]

# Bot calls evaluate_python_code with:
def twoSum(nums, target):
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]

# Test cases:
result = twoSum([2, 7, 11, 15], 9)  # Should be [0, 1]
result = twoSum([3, 3], 6)          # Edge case: duplicates
result = twoSum([], 0)              # Edge case: empty
result = twoSum([1], 1)             # Edge case: single element

# Bot shows output, errors, and feedback

Bot always evaluates code to:

  • Catch syntax/runtime errors
  • Show actual output vs expected
  • Test edge cases user might miss
  • Demonstrate performance issues (slow code)

Memory Keys

Tutor stores data with structured keys:

  • problem_two_sum — Problem details
  • solution_attempt_1 — First solution code
  • solution_attempt_2 — Refined solution
  • complexity_analysis_two_sum — Time/space complexity notes
  • approach_notes_two_sum — Strategy discussions

Retrieve with: get_from_memory('problem_two_sum')

Development

No test suite. Manual testing via gradio_test.py.

To add new tools:

  1. Define function in tools/pandora_functions.py with Annotated type hints
  2. Add to pandora_tools list in tools/__init__.py
  3. Update prompt if new behavior needed

Logs

# Debug logging
LOGGING_LEVEL=DEBUG uv run python gradio_test.py

Environment Variables

Required:

  • OPENAI_API_KEY (or Azure/OpenRouter equivalent)

Optional:

  • LOGGING_LEVEL — Set to DEBUG for verbose logs

Notes

  • Memory persists across sessions in pandora.data/ directory
  • Code evaluation runs with: math, random, datetime, json, re, numpy in scope
  • Web search uses DuckDuckGo (no API key needed)
  • Problem fetching works with any HTML-based problem site

About

Agentic AI tutor that coaches you through coding problems — never just gives you the answer

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages