Athagi commited on
Commit
5afdcff
·
verified ·
1 Parent(s): 646abb1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -81
app.py CHANGED
@@ -1,88 +1,106 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>AGI Terminal</title>
7
- <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
8
- </head>
9
- <body>
10
- <div class="terminal-container">
11
- <div class="chat-output" id="chat">
12
- <div class="message system">
13
- 🤖 AGI Terminal Ready<br>
14
- Available commands:<br>
15
- - AI: [your question]<br>
16
- - file:list<br>
17
- - ![command]
18
- </div>
19
- </div>
20
-
21
- <div class="input-container">
22
- <div class="prompt">>></div>
23
- <input type="text" id="command-input" autofocus>
24
- <button onclick="executeCommand()">Execute</button>
25
- </div>
26
- </div>
27
 
28
- <script>
29
- const chat = document.getElementById('chat');
30
- const input = document.getElementById('command-input');
31
 
32
- async function executeCommand() {
33
- const command = input.value.trim();
34
- if (!command) return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- addMessage(command, 'user');
37
- input.value = '';
 
 
 
 
 
 
 
 
38
 
39
- const loader = addLoader();
 
 
 
40
 
41
- try {
42
- const response = await fetch('/execute', {
43
- method: 'POST',
44
- headers: {'Content-Type': 'application/json'},
45
- body: JSON.stringify({ code: command })
46
- });
47
-
48
- const data = await response.json();
49
- loader.remove();
50
-
51
- handleResponse(data);
52
-
53
- } catch (error) {
54
- loader.remove();
55
- addMessage(`Error: ${error.message}`, 'error');
56
- }
57
- }
58
-
59
- function handleResponse(data) {
60
- let content = data.result;
61
- if (data.type === 'code') {
62
- content += `<br><a href="/download/${data.file}" download class="download-link">Download ${data.file}</a>`;
63
- }
64
- addMessage(content, data.type);
65
- }
66
-
67
- function addMessage(content, type) {
68
- const div = document.createElement('div');
69
- div.className = `message ${type}`;
70
- div.innerHTML = content;
71
- chat.appendChild(div);
72
- chat.scrollTop = chat.scrollHeight;
73
- }
74
 
75
- function addLoader() {
76
- const loader = document.createElement('div');
77
- loader.className = 'message loader';
78
- loader.innerHTML = '<div class="dot-flashing"></div>';
79
- chat.appendChild(loader);
80
- return loader;
81
- }
82
 
83
- input.addEventListener('keypress', (e) => {
84
- if (e.key === 'Enter') executeCommand();
85
- });
86
- </script>
87
- </body>
88
- </html>
 
1
+ from flask import Flask, request, jsonify, render_template, send_from_directory
2
+ import os
3
+ import subprocess
4
+ import tempfile
5
+ import google.generativeai as genai
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ app = Flask(__name__)
8
+ temp_dir = tempfile.mkdtemp()
9
+ current_dir = temp_dir
10
 
11
+ # Configure Google Generative AI
12
+ genai.configure(api_key=os.environ["GEMINI_API_KEY"])
13
+
14
+ # Create the model
15
+ generation_config = {
16
+ "temperature": 1,
17
+ "top_p": 0.95,
18
+ "top_k": 64,
19
+ "max_output_tokens": 8192,
20
+ "response_mime_type": "text/plain",
21
+ }
22
+
23
+ model = genai.GenerativeModel(
24
+ model_name="gemini-1.5-pro-latest",
25
+ generation_config=generation_config,
26
+ system_instruction="You are an AGI assistant. Follow these rules:\n1. Respond with executable code when asked to create files\n2. Use Python code blocks for scripts\n3. Use bash code blocks for terminal commands\n4. Keep responses concise and actionable"
27
+ )
28
+
29
+ chat_session = model.start_chat(history=[])
30
+
31
+ def execute_command(command, cwd=None):
32
+ process = subprocess.Popen(
33
+ command,
34
+ shell=True,
35
+ stdout=subprocess.PIPE,
36
+ stderr=subprocess.PIPE,
37
+ text=True,
38
+ cwd=cwd or current_dir
39
+ )
40
+ stdout, stderr = process.communicate()
41
+ return stdout + stderr
42
+
43
+ @app.route("/")
44
+ def index():
45
+ return render_template("index.html")
46
+
47
+ def handle_code_response(response):
48
+ python_code = []
49
+ for part in response.parts:
50
+ if "```python" in part.text:
51
+ code = part.text.split("```python")[1].split("```")[0].strip()
52
+ python_code.append(code)
53
+ return python_code
54
+
55
+ @app.route("/execute", methods=["POST"])
56
+ def execute_code():
57
+ command = request.json.get("code", "").strip()
58
+ if not command:
59
+ return jsonify({"result": "Error: No command provided."})
60
+
61
+ try:
62
+ if command.lower().startswith(("ai:", "/ai")):
63
+ prompt = command.split(":", 1)[1].strip()
64
+ response = chat_session.send_message(prompt)
65
 
66
+ python_code = handle_code_response(response)
67
+ if python_code:
68
+ filename = "generated_script.py"
69
+ with open(os.path.join(current_dir, filename), "w") as f:
70
+ f.write("\n".join(python_code))
71
+ return jsonify({
72
+ "result": response.text,
73
+ "type": "code",
74
+ "file": filename
75
+ })
76
 
77
+ return jsonify({
78
+ "result": response.text,
79
+ "type": "text"
80
+ })
81
 
82
+ elif command.lower().startswith(("file:", "/file")):
83
+ _, operation = command.split(":", 1)
84
+ if "list" in operation:
85
+ return jsonify({
86
+ "result": "\n".join(os.listdir(current_dir)),
87
+ "type": "file_list"
88
+ })
89
+ return jsonify({"result": "Unsupported file operation", "type": "error"})
90
+
91
+ elif command.startswith("!"):
92
+ result = execute_command(command[1:])
93
+ return jsonify({"result": result, "type": "command_output"})
94
+
95
+ else:
96
+ return jsonify({"result": "Unrecognized command. Type 'help' for options.", "type": "error"})
97
+
98
+ except Exception as e:
99
+ return jsonify({"result": f"Error: {str(e)}", "type": "error"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ @app.route("/download/<path:filename>")
102
+ def download_file(filename):
103
+ return send_from_directory(current_dir, filename, as_attachment=True)
 
 
 
 
104
 
105
+ if __name__ == "__main__":
106
+ app.run(host="0.0.0.0", port=7860)