File size: 13,549 Bytes
12449aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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 environment variables
load_dotenv()
GROQ_API_KEY = os.getenv("GROQ_API_KEY")

if not GROQ_API_KEY:
    raise ValueError("GROQ_API_KEY tidak ditemukan di .env")

# Initialize Flask app
app = Flask(__name__)

# Initialize OpenAI client
client = OpenAI(
    base_url="https://api.groq.com/openai/v1",
    api_key=GROQ_API_KEY
)

# Database initialization (gunakan SQLite atau pustaka lainnya)
# Misalnya, untuk menyimpan riwayat percakapan
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 Base (ambil dari kode asli)
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 (gunakan dari kode asli Anda)
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():
    # Serve index.html
    return send_from_directory('.', 'index.html')

@app.route('/<path:path>')
def static_files(path):
    # Serve static files (CSS, JS, etc.)
    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') # Default model
        thinking_mode = data.get('mode', 'default') # Default mode

        if not user_message:
            return jsonify({"error": "Message is required"}), 400

        # Prepare messages for API call
        system_message = {"role": "system", "content": SYSTEM_PROMPTS.get(thinking_mode, SYSTEM_PROMPTS["default"])}
        messages = [system_message, {"role": "user", "content": user_message}]

        # Call Groq API
        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

        # Optional: Save to database
        # c.execute("INSERT INTO chat_history (conversation_id, role, content) VALUES (?, ?, ?)",
        #          (1, "user", user_message))
        # c.execute("INSERT INTO chat_history (conversation_id, role, content) VALUES (?, ?, ?)",
        #          (1, "assistant", ai_response))
        # conn.commit()

        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) # Hugging Face Spaces akan menggunakan port ini