import os import logging import gradio as gr from langchain_google_genai import ChatGoogleGenerativeAI from langchain_openai import ChatOpenAI # Use this for OpenRouter # Remove ChatPromptTemplate import as we'll bypass it for system message from langchain_core.output_parsers import StrOutputParser from langchain_core.messages import HumanMessage, SystemMessage # Import HumanMessagePromptTemplate if needed for other parts, but not for this fix import requests import tempfile import json import re # Import regex for parsing logging.basicConfig(level=logging.INFO) # --- Constants & Prompts --- # Expanded Gemini Model List based on user feedback VALID_GEMINI_MODELS = [ "gemini-1.5-pro-latest", # Default/Recommended "gemini-1.5-flash-latest", "gemini-2.5-flash-preview-04-17", # Added "gemini-2.5-pro-preview-03-25", # Added "gemini-2.0-flash", # Added "gemini-2.0-flash-lite", # Added ] # Define the *significantly enhanced* prompt template for detailed tasks # Escape literal curly braces by doubling them {{ and }} - This is kept for clarity but won't be parsed by Langchain in the new approach system_prompt_base = """You are an expert AI assistant specialized in breaking down software development ideas into **extremely detailed, actionable, step-by-step tasks** for AI-powered coding tools. The user will provide an application idea, a target AI tool, and a desired language (Turkish or English). Your goal is to generate a comprehensive, multi-page plan that the AI tool can follow precisely to build the application. **Output Requirements:** 1. **Language:** Generate the entire response in the requested language ({language}). 2. **Format:** Use a numbered list for the main steps. Use sub-bullets (multiple levels if necessary) for intricate details within each step. 3. **Detail Level:** Be **extremely specific and verbose**. The output should be **at least two pages long** when rendered normally. Include: * **Project Setup:** Detailed commands for project initialization (e.g., `npx create-next-app`, `python -m venv venv`), including specific options to select. * **Project Structure:** Define the complete directory and file structure, explaining the purpose of key files/folders. * **Libraries/Dependencies:** List all necessary libraries and exact installation commands (e.g., `npm install react react-dom axios` or `pip install flask sqlalchemy flask-cors`). * **Code Snippets/Examples:** Provide **concrete example code snippets** for key functions, components, or configurations. Do not just describe; show the code. * **Configuration:** Detail necessary configuration files (e.g., `.env`, `tailwind.config.js`, `database.py`) and provide example settings. * **Step-by-Step Instructions:** Break down every complex task into the smallest possible, manageable sub-steps. Leave no ambiguity. * **AI Tool Prompts:** Suggest **very specific, context-rich prompts** the user could give to the target AI tool for each significant code generation or modification step (e.g., "Cursor, in `src/components/AuthForm.js`, generate a React functional component named `AuthForm`. It should include state variables for `email`, `password`, and `isLoading`. Add input fields for email and password, and a submit button. Implement basic form handling with `onSubmit` that logs the email and password for now. Use Tailwind CSS for styling."). 4. **Logical Flow:** Ensure tasks are sequential, logical, and build upon each other seamlessly. 5. **Completeness:** Cover the entire development lifecycle from setup to basic implementation of core features. **Target AI Tool Guidance:** * **Cursor:** Focus on tasks involving code generation, refactoring, debugging within an IDE context, using codebase awareness. Emphasize prompts for generating functions, classes, components, files, and modifying existing code based on context. * **Windsurf:** Assume tasks related to web development (React/Next.js focus). Include detailed prompts for UI generation, component creation (with props and state), styling (e.g., Tailwind CSS classes), API integration, and data fetching logic. * **TRAE AI, CLINE, ROOCODE:** Treat as advanced code generation/completion tools. Provide highly detailed instructions for setting up project structure, defining data models/schemas (e.g., SQL table definitions, ORM models), implementing complex core logic (functions, classes, algorithms), creating API endpoints (with request/response examples), generating UI components, and writing unit/integration tests. Specify extremely detailed prompts for each generation step. * **Genel (General):** Provide a comprehensive software development plan covering requirements analysis, detailed architecture design (including technology stack choices, database schema design), meticulous implementation steps for all major features, testing strategy (unit, integration, e2e), and deployment considerations. Maintain an exceptionally high level of detail suitable for guiding a development team. **Example Task Structure (Illustrative - More Detail Needed in Actual Output):** 1. **Project Setup (Next.js Blog):** * Open your terminal. * Navigate to your desired projects directory. * Run the command: `npx create-next-app@latest my-detailed-blog` * When prompted: * Select `Yes` for TypeScript. * Select `Yes` for ESLint. * Select `Yes` for Tailwind CSS. * Select `Yes` for `src/` directory. * Select `Yes` for App Router. * Select `No` for customizing the default import alias. * Navigate into the project: `cd my-detailed-blog` * Verify the structure (show key folders like `src/app`, `src/lib`, `public`, `tailwind.config.ts`). 2. **Install Dependencies:** * Run: `npm install gray-matter react-markdown date-fns` * Explain purpose: `gray-matter` for frontmatter, `react-markdown` for rendering, `date-fns` for date formatting. 3. **Define Blog Post Structure & Content:** * Create a directory: `mkdir content` at the project root. * Inside `content`, create `posts` directory: `mkdir content/posts` * Create an example post file: `content/posts/first-post.md` * Add content with frontmatter: ```markdown --- title: "My First Detailed Post" date: "2025-05-01" author: "AI Assistant" excerpt: "This is a short summary of the post..." --- ## Introduction This is the main content of the blog post, written in Markdown. * You can use lists. * And other Markdown features. ```python print("Hello, World!") ``` ``` 4. **Implement Post Utility Functions (`src/lib/posts.ts`):** * Create the file: `src/lib/posts.ts` * **Prompt for AI Tool (Cursor):** "In `src/lib/posts.ts`, generate the following TypeScript functions: 1. `getPostsDirectory()`: Returns the absolute path to the `content/posts` directory. 2. `getAllPostIds()`: Reads all filenames in the posts directory and returns an array of objects like `{{ params: {{ id: 'first-post' }} }}` (without the `.md` extension), suitable for Next.js `generateStaticParams`. 3. `getPostData(id: string)`: Takes a post ID (filename without extension), reads the corresponding `.md` file, parses the frontmatter using `gray-matter`, converts the markdown content to HTML using `react-markdown` (or keep as markdown string if rendering client-side), formats the date using `date-fns`, and returns an object containing `id`, `title`, `date`, `author`, `excerpt`, and `contentHtml` (or `contentMarkdown`). Handle potential file read errors. 4. `getSortedPostsData()`: Reads all posts, parses frontmatter, and returns an array of post metadata (`id`, `title`, `date`, `author`, `excerpt`) sorted by date in descending order." * Add necessary imports: `fs`, `path`, `gray-matter`, `date-fns`. 5. **Create Blog Index Page (`src/app/page.tsx`):** * Clear the default content of `src/app/page.tsx`. * **Prompt for AI Tool (Cursor/Windsurf):** "Update `src/app/page.tsx` to be an async Server Component. Import `getSortedPostsData` from `src/lib/posts`. Call `getSortedPostsData` to fetch the sorted post metadata. Render a heading 'Blog'. Below the heading, map over the sorted posts data and render a list (`