Skip to content

Acharya-Arvind/Leetcode-Agent

Repository files navigation

Autonomous LeetCode Solver Agent

This repository contains a modular, autonomous AI agent built with Next.js. It fetches LeetCode problems, generates optimal code using a pluggable AI model (Gemini by default), tests the code locally, and optionally submits it to LeetCode via browser automation (Playwright).

The project is designed for research and demonstration; it can be extended to support new models, languages, or problem sources. A login with LeetCode credentials is used for submission so the agent can run end‑to‑end.


🚀 Features

  • Fetch problem data (title, description, examples, constraints) using LeetCode's GraphQL API
  • Analyze and solve problems with an AI model (Gemini/OpenAI or custom)
  • Self‑correcting loop: retest and fix until examples pass (max 3 attempts)
  • Local Python test runner for example cases
  • Submit solutions to LeetCode with Playwright browser automation
  • Detailed event logging streamed to frontend
  • Clean, modular codebase with TypeScript types and agent abstractions
  • Easy model swap by changing AI_PROVIDER env variable

🛠️ Getting Started

1. Clone the repo

git clone <your-repo-url>
cd leetcode-agent

2. Install dependencies

npm install
# or yarn

3. Configure environment

Copy the example and fill in your keys:

cp .env.example .env.local

Edit .env.local:

# AI
AI_PROVIDER=gemini              # or openai
GEMINI_API_KEY=your_gemini_key
# OPENAI_API_KEY=your_openai_key

# LeetCode credentials for auto‑submit
LEETCODE_USERNAME=your_email_or_username
LEETCODE_PASSWORD=your_password

# Optional tuning
AI_TEMPERATURE=0.2
AI_MAX_TOKENS=4096

Note: .env.local is ignored by Git; never commit your keys or passwords.

4. (Optional) Install Playwright browsers

npx playwright install chromium

5. Run the development server

npm run dev

Open http://localhost:3000 in your browser.


📦 Project Structure

src/
├─ app/
│   ├─ api/solve/route.ts       # POST endpoint for solving
│   ├─ page.tsx                 # frontend UI
│   └─ layout.tsx
├─ lib/
│   ├─ ai/                      # AI model abstraction & adapters
│   ├─ agents/                  # Fetch, solve, test, submit, orchestrator
│   ├─ leetcode/                # GraphQL client & Playwright helpers
│   ├─ config.ts               # env variable loader
│   └─ types/index.ts          # shared TS interfaces
└─ .env.example

🧠 How it works

  1. Fetch: FetchProblemAgent retrieves the problem using the LeetCode GraphQL API.
  2. Solve: SolveProblemAgent prompts the AI model with the description and examples.
  3. Test: TestCodeAgent runs solution against example inputs locally (Python only).
  4. Fix: If tests fail, the agent asks the model to correct the code (up to 3 retries).
  5. Submit (optional): SubmitCodeAgent logs into LeetCode with provided credentials and submits the code via Playwright.
  6. Orchestrator (OrchestratorAgent) ties all steps together and streams events to the frontend.

🔁 Swapping AI Models

Change AI_PROVIDER in .env.local to gemini or openai. Add more by:

  1. Creating a new adapter in src/lib/ai/ extending BaseAIModel.
  2. Registering it in src/lib/ai/index.ts.
  3. Setting the corresponding API key and model name in env.

✅ Example Usage

  1. Visit homepage.
  2. Enter problem number (e.g. 1 for Two Sum).
  3. Select language (Python, JS, etc.).
  4. Check Auto-Submit if you configured LeetCode creds.
  5. Click Solve.

Logs will appear in real time; solution code, test results, and submission status are displayed.


⚠️ Limitations & Notes

  • Local testing supports Python only; other languages skip testing and rely on submission.
  • LeetCode login may fail if 2‑factor authentication is enabled or if captcha appears.
  • AI-generated code may occasionally be incorrect; review before submitting if unsure.
  • The project is meant for personal learning and demonstration. Respect LeetCode's terms of service.

Troubleshooting API Errors

If you see an HTTP error from /api/solve, here's what it usually means:

Status Common Cause What to Do
400 Bad Request Invalid input (missing/empty problem number, unsupported language) Make sure you typed a positive integer and chose a supported language. The frontend normally prevents this, but manual requests or malformed JSON can trigger it.
500 Internal Server Error Something went wrong during fetching, solving, or submission (e.g. network failure, AI service error, invalid LeetCode credentials) Check the browser console or server logs for the detailed message. GraphQL failures (400) will print the response body to the server console. Ensure your .env.local is configured correctly and your network is reachable.

In the browser, error messages returned by the API are displayed at the top of the page. The live log panel will also capture server events for debugging.


🛡️ Security

Never share your .env.local. The only sensitive data stored are:

  • AI API keys
  • LeetCode username/password

For production or research, consider using encrypted secrets stores.


📘 License

MIT

Feel free to build upon or adapt this project for your own experiments! Happy coding 🎯

About

Autonomous AI‑powered LeetCode assistant built with Next.js

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages