| from flask import Flask, request, jsonify, send_from_directory |
| from openai import OpenAI |
| import os |
| import json |
| import sqlite3 |
| from dotenv import load_dotenv |
| import time |
|
|
| |
| load_dotenv() |
| GROQ_API_KEY = os.getenv("GROQ_API_KEY") |
|
|
| if not GROQ_API_KEY: |
| raise ValueError("GROQ_API_KEY tidak ditemukan di .env") |
|
|
| |
| app = Flask(__name__) |
|
|
| |
| client = OpenAI( |
| base_url="https://api.groq.com/openai/v1", |
| api_key=GROQ_API_KEY |
| ) |
|
|
| |
| |
| conn = sqlite3.connect('chat_history.db', check_same_thread=False) |
| c = conn.cursor() |
| c.execute('''CREATE TABLE IF NOT EXISTS chat_history |
| (id INTEGER PRIMARY KEY AUTOINCREMENT, |
| conversation_id INTEGER, |
| role TEXT, |
| content TEXT, |
| timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''') |
| conn.commit() |
|
|
| |
| LANGUAGE_KNOWLEDGE = { |
| "python": { |
| "frameworks": ["Django", "Flask", "FastAPI", "Streamlit", "PyQt", "Tkinter"], |
| "paradigms": ["OOP", "Functional", "Procedural", "Imperative"], |
| "extension": ".py", |
| "hello_world": "print('Hello, World!')", |
| "package_manager": "pip", |
| "runtime": "CPython, PyPy, Jython", |
| "typing": "Dynamic, Optional Static (Type hints)", |
| "use_cases": ["Web Development", "Data Science", "AI/ML", "Automation", "Scripting"], |
| "special_notes": "Interpreted language with extensive libraries. Great for beginners and rapid prototyping." |
| }, |
| "javascript": { |
| "frameworks": ["React", "Vue", "Angular", "Node.js", "Express", "Next.js", "Svelte"], |
| "paradigms": ["OOP", "Functional", "Event-driven", "Prototype-based"], |
| "extension": ".js", |
| "hello_world": "console.log('Hello, World!');", |
| "package_manager": "npm/yarn", |
| "runtime": "Node.js, Browser V8", |
| "typing": "Dynamic, Optional Static (TypeScript)", |
| "use_cases": ["Web Frontend", "Backend", "Mobile Apps", "Desktop Apps"], |
| "special_notes": "The language of the web. Runs everywhere from browsers to servers." |
| }, |
| "typescript": { |
| "frameworks": ["Angular", "React", "Vue", "NestJS"], |
| "paradigms": ["OOP", "Functional", "Event-driven"], |
| "extension": ".ts", |
| "hello_world": "console.log('Hello, World!');", |
| "package_manager": "npm/yarn", |
| "runtime": "Node.js, Browser (compiled to JS)", |
| "typing": "Static, Strong", |
| "use_cases": ["Large-scale Web Apps", "Enterprise Applications"], |
| "special_notes": "JavaScript with static typing. Catches errors at compile time." |
| }, |
| "java": { |
| "frameworks": ["Spring", "Hibernate", "Jakarta EE", "Quarkus", "Micronaut"], |
| "paradigms": ["OOP", "Concurrent", "Imperative"], |
| "extension": ".java", |
| "hello_world": 'public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } }', |
| "package_manager": "Maven/Gradle", |
| "runtime": "JVM (Java Virtual Machine)", |
| "typing": "Static, Strong", |
| "use_cases": ["Enterprise Applications", "Android Apps", "Big Data", "Banking Systems"], |
| "special_notes": "Write once, run anywhere. Strong emphasis on OOP and platform independence." |
| }, |
| "lua": { |
| "frameworks": ["LΓVE", "Corona SDK", "MOAI"], |
| "paradigms": ["Procedural", "OOP", "Functional", "Data-driven"], |
| "extension": ".lua", |
| "hello_world": "print('Hello, World!')", |
| "package_manager": "LuaRocks", |
| "runtime": "Lua VM", |
| "typing": "Dynamic, Weak", |
| "use_cases": ["Game Development", "Embedded Systems", "Scripting", "Configuration"], |
| "special_notes": "Lightweight, embeddable scripting language. Often used in games and applications." |
| }, |
| "luau": { |
| "frameworks": ["Roblox Studio"], |
| "paradigms": ["OOP", "Procedural", "Data-driven"], |
| "extension": ".lua", |
| "hello_world": "print('Hello, World!')", |
| "package_manager": "Roblox Studio", |
| "runtime": "Roblox Engine", |
| "typing": "Dynamic with optional type annotations", |
| "use_cases": ["Roblox Game Development", "Game Scripting"], |
| "special_notes": "Luau is a scripting language derived from Lua 5.1, used primarily for Roblox game development. Has gradual typing and performance optimizations." |
| }, |
| "html": { |
| "frameworks": ["Bootstrap", "Tailwind CSS", "Foundation"], |
| "paradigms": ["Markup", "Declarative"], |
| "extension": ".html", |
| "hello_world": "<!DOCTYPE html><html><head><title>Hello</title></head><body><h1>Hello, World!</h1></body></html>", |
| "package_manager": "None", |
| "runtime": "Web Browser", |
| "typing": "None", |
| "use_cases": ["Web Pages", "Web Applications", "Email Templates"], |
| "special_notes": "Markup language for creating web pages. Not a programming language." |
| }, |
| "css": { |
| "frameworks": ["Bootstrap", "Tailwind CSS", "Sass", "Less"], |
| "paradigms": ["Styling", "Declarative"], |
| "extension": ".css", |
| "hello_world": "body { color: blue; font-family: Arial; }", |
| "package_manager": "npm (for preprocessors)", |
| "runtime": "Web Browser", |
| "typing": "None", |
| "use_cases": ["Web Styling", "Responsive Design", "Animations"], |
| "special_notes": "Style sheet language for describing presentation of documents." |
| }, |
| "cpp": { |
| "frameworks": ["Qt", "Boost", "STL", "Unreal Engine"], |
| "paradigms": ["OOP", "Procedural", "Generic", "Functional"], |
| "extension": ".cpp", |
| "hello_world": """#include <iostream> |
| int main() { std::cout << "Hello, World!"; return 0; }""", |
| "package_manager": "vcpkg/conan", |
| "runtime": "Native Compilation", |
| "typing": "Static, Strong", |
| "use_cases": ["System Programming", "Game Development", "High-Performance Computing", "Embedded Systems"], |
| "special_notes": "Extension of C with OOP features. High performance, manual memory management." |
| }, |
| "rust": { |
| "frameworks": ["Actix", "Rocket", "Tokio"], |
| "paradigms": ["Multi-paradigm", "Functional", "Concurrent"], |
| "extension": ".rs", |
| "hello_world": """fn main() { println!("Hello, World!"); }""", |
| "package_manager": "Cargo", |
| "runtime": "Native Compilation", |
| "typing": "Static, Strong", |
| "use_cases": ["System Programming", "Web Assembly", "CLI Tools", "Networking"], |
| "special_notes": "Memory safety without garbage collection. Zero-cost abstractions." |
| }, |
| "go": { |
| "frameworks": ["Gin", "Echo", "Fiber"], |
| "paradigms": ["Concurrent", "Procedural", "Imperative"], |
| "extension": ".go", |
| "hello_world": """package main |
| import "fmt" |
| func main() { fmt.Println("Hello, World!") }""", |
| "package_manager": "Go Modules", |
| "runtime": "Native Compilation", |
| "typing": "Static, Strong", |
| "use_cases": ["Backend Services", "CLI Tools", "Networking", "Cloud Native"], |
| "special_notes": "Simple syntax, built-in concurrency, fast compilation." |
| }, |
| "php": { |
| "frameworks": ["Laravel", "Symfony", "CodeIgniter"], |
| "paradigms": ["OOP", "Procedural", "Functional"], |
| "extension": ".php", |
| "hello_world": "<?php echo 'Hello, World!'; ?>", |
| "package_manager": "Composer", |
| "runtime": "Zend Engine", |
| "typing": "Dynamic, Optional Static", |
| "use_cases": ["Web Development", "WordPress", "E-commerce"], |
| "special_notes": "Server-side scripting language designed for web development." |
| }, |
| "ruby": { |
| "frameworks": ["Ruby on Rails", "Sinatra", "Hanami"], |
| "paradigms": ["OOP", "Functional", "Metaprogramming"], |
| "extension": ".rb", |
| "hello_world": "puts 'Hello, World!'", |
| "package_manager": "RubyGems", |
| "runtime": "MRI, JRuby", |
| "typing": "Dynamic, Duck Typing", |
| "use_cases": ["Web Development", "Scripting", "DevOps"], |
| "special_notes": "Developer happiness focus. 'Everything is an object' philosophy." |
| }, |
| "swift": { |
| "frameworks": ["SwiftUI", "UIKit", "Vapor"], |
| "paradigms": ["OOP", "Protocol-oriented", "Functional"], |
| "extension": ".swift", |
| "hello_world": 'print("Hello, World!")', |
| "package_manager": "Swift Package Manager", |
| "runtime": "Native Compilation", |
| "typing": "Static, Strong", |
| "use_cases": ["iOS/macOS Apps", "Server-side", "System Programming"], |
| "special_notes": "Modern language by Apple. Safe by design, fast performance." |
| }, |
| "kotlin": { |
| "frameworks": ["Spring", "Ktor", "Android SDK"], |
| "paradigms": ["OOP", "Functional"], |
| "extension": ".kt", |
| "hello_world": 'fun main() { println("Hello, World!") }', |
| "package_manager": "Gradle", |
| "runtime": "JVM, Native, JS", |
| "typing": "Static, Strong", |
| "use_cases": ["Android Development", "Backend Services", "Multiplatform"], |
| "special_notes": "Modern language that interoperates with Java. Null safety features." |
| } |
| } |
|
|
| |
| SYSTEM_PROMPTS = { |
| "default": "You are a helpful AI assistant.", |
| "coder": ( |
| "You are an AI Coder Specialist with exceptional coding skills. Use this language knowledge base for reference:\n" |
| + json.dumps(LANGUAGE_KNOWLEDGE, indent=2) + |
| "\nFollow this structure:\nπ§ ANALYZE:\n- Understand the problem and requirements\n- Identify constraints and edge cases\nπ PLAN:\n" |
| "- Create pseudocode or algorithm\n- Determine optimal data structures\n- Plan the solution architecture\nπ» IMPLEMENT:\n" |
| "- Write code using best practices\n- Use clear naming conventions\n- Add informative comments\nπ EXPLAIN:\n" |
| "- Explain the solution in detail\n- Include a complexity analysis\n- Provide alternative solutions\nFormat the output with clear sections." |
| ), |
| "builder": """You are an AI Builder/Architect. Follow this methodology: |
| π‘ IDEA GENERATION: |
| - Brainstorm ideas and concepts |
| - Evaluate feasibility |
| - Identify unique value proposition |
| ποΈ ARCHITECTURE DESIGN: |
| - System design and components |
| - Database schema (if necessary) |
| - API design and endpoints |
| π DEVELOPMENT PLAN: |
| - Task breakdown |
| - Timeline estimation |
| - Technology stack recommendation |
| β‘ EXECUTION GUIDANCE: |
| - Step-by-step implementation |
| - Best practices |
| - Testing strategy""", |
| "replit_agent": ( |
| "You are Replit AI Agent - an autonomous AI that can build complete applications from natural language descriptions.\n" |
| + "Use this language knowledge base:\n" |
| + json.dumps(LANGUAGE_KNOWLEDGE, indent=2) + |
| """ |
| YOUR CAPABILITIES: |
| 1. Application Creation from Natural Language |
| 2. Multi-step Autonomy (Environment setup, coding, testing, deployment) |
| 3. Automatic Testing and Debugging |
| 4. Real-time Code Suggestions |
| 5. Code Explanation |
| 6. Multi-language Support (Python, JavaScript, HTML, CSS, etc.) |
| 7. Checkpoint Management |
| WORKFLOW: |
| 1. UNDERSTAND: Parse the user's natural language request for an application |
| 2. PLAN: Create a detailed development plan with steps |
| 3. SETUP: Prepare environment and create necessary files |
| 4. IMPLEMENT: Write code for all components |
| 5. TEST: Create and run tests |
| 6. DEBUG: Identify and fix issues |
| 7. DEPLOY: Provide deployment instructions |
| Always provide: |
| - Clear step-by-step plan |
| - Complete code files |
| - Testing strategy |
| - Deployment options |
| - Checkpoint suggestions |
| You can manage multiple files and create full-stack applications.""" |
| ) |
| } |
|
|
| @app.route('/') |
| def index(): |
| |
| return send_from_directory('.', 'index.html') |
|
|
| @app.route('/<path:path>') |
| def static_files(path): |
| |
| return send_from_directory('.', path) |
|
|
| @app.route('/chat', methods=['POST']) |
| def chat(): |
| try: |
| data = request.json |
| user_message = data.get('message') |
| model_id = data.get('model', 'qwen/qwen3-32b') |
| thinking_mode = data.get('mode', 'default') |
|
|
| if not user_message: |
| return jsonify({"error": "Message is required"}), 400 |
|
|
| |
| system_message = {"role": "system", "content": SYSTEM_PROMPTS.get(thinking_mode, SYSTEM_PROMPTS["default"])} |
| messages = [system_message, {"role": "user", "content": user_message}] |
|
|
| |
| response = client.chat.completions.create( |
| model=model_id, |
| messages=messages, |
| temperature=0.7, |
| max_tokens=8192, |
| top_p=0.9 |
| ) |
|
|
| ai_response = response.choices[0].message.content |
|
|
| |
| |
| |
| |
| |
| |
|
|
| return jsonify({"response": ai_response}) |
|
|
| except Exception as e: |
| return jsonify({"error": str(e)}), 500 |
|
|
| if __name__ == '__main__': |
| app.run(host='0.0.0.0', port=7860, debug=True) |