acecalisto3 commited on
Commit
cb052d2
1 Parent(s): 2efafeb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +280 -379
app.py CHANGED
@@ -2,10 +2,29 @@ import os
2
  import subprocess
3
  import streamlit as st
4
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
5
- import black
6
- from pylint import lint
 
 
 
 
 
 
7
  from io import StringIO
8
-
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
10
  PROJECT_ROOT = "projects"
11
  AGENT_DIRECTORY = "agents"
@@ -25,387 +44,269 @@ if 'current_state' not in st.session_state:
25
  'workspace_chat': {}
26
  }
27
 
28
- class AIAgent:
29
- def __init__(self, name, description, skills):
30
- self.name = name
31
- self.description = description
32
- self.skills = skills
33
-
34
- def create_agent_prompt(self):
35
- skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
36
- agent_prompt = f"""
37
- As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
38
- {skills_str}
39
-
40
- I am confident that I can leverage my expertise to assist you in developing and deploying cutting-edge web applications. Please feel free to ask any questions or present any challenges you may encounter.
41
- """
42
- return agent_prompt
43
-
44
- def autonomous_build(self, chat_history, workspace_projects):
45
- """
46
- Autonomous build logic that continues based on the state of chat history and workspace projects.
47
- """
48
- summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
49
- summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
50
-
51
- next_step = "Based on the current state, the next logical step is to implement the main application logic."
52
-
53
- return summary, next_step
54
-
55
- def save_agent_to_file(agent):
56
- """Saves the agent's prompt to a file locally and then commits to the Hugging Face repository."""
57
- if not os.path.exists(AGENT_DIRECTORY):
58
- os.makedirs(AGENT_DIRECTORY)
59
- file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
60
- config_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}Config.txt")
61
- with open(file_path, "w") as file:
62
- file.write(agent.create_agent_prompt())
63
- with open(config_path, "w") as file:
64
- file.write(f"Agent Name: {agent.name}\nDescription: {agent.description}")
65
- st.session_state.available_agents.append(agent.name)
66
-
67
- commit_and_push_changes(f"Add agent {agent.name}")
68
-
69
- def load_agent_prompt(agent_name):
70
- """Loads an agent prompt from a file."""
71
- file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
72
- if os.path.exists(file_path):
73
- with open(file_path, "r") as file:
74
- agent_prompt = file.read()
75
- return agent_prompt
76
  else:
77
- return None
78
-
79
- def create_agent_from_text(name, text):
80
- skills = text.split('\n')
81
- agent = AIAgent(name, "AI agent created from text input.", skills)
82
- save_agent_to_file(agent)
83
- return agent.create_agent_prompt()
84
-
85
- # Chat interface using a selected agent
86
- def chat_interface_with_agent(input_text, agent_name):
87
- agent_prompt = load_agent_prompt(agent_name)
88
- if agent_prompt is None:
89
- return f"Agent {agent_name} not found."
90
-
91
- # Load the GPT-2 model which is compatible with AutoModelForCausalLM
92
- model_name = "gpt2"
93
  try:
94
- model = AutoModelForCausalLM.from_pretrained(model_name)
95
- tokenizer = AutoTokenizer.from_pretrained(model_name)
96
- generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
97
- except EnvironmentError as e:
98
- return f"Error loading model: {e}"
99
-
100
- # Combine the agent prompt with user input
101
- combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
102
-
103
- # Truncate input text to avoid exceeding the model's maximum length
104
- max_input_length = 900
105
- input_ids = tokenizer.encode(combined_input, return_tensors="pt")
106
- if input_ids.shape[1] > max_input_length:
107
- input_ids = input_ids[:, :max_input_length]
108
-
109
- # Generate chatbot response
110
- outputs = model.generate(
111
- input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True, pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id
112
- )
113
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
114
- return response
115
-
116
- def workspace_interface(project_name):
117
- project_path = os.path.join(PROJECT_ROOT, project_name)
118
- if not os.path.exists(PROJECT_ROOT):
119
- os.makedirs(PROJECT_ROOT)
120
- if not os.path.exists(project_path):
121
- os.makedirs(project_path)
122
- st.session_state.workspace_projects[project_name] = {"files": []}
123
- st.session_state.current_state['workspace_chat']['project_name'] = project_name
124
- commit_and_push_changes(f"Create project {project_name}")
125
- return f"Project {project_name} created successfully."
126
- else:
127
- return f"Project {project_name} already exists."
128
-
129
- def add_code_to_workspace(project_name, code, file_name):
130
- project_path = os.path.join(PROJECT_ROOT, project_name)
131
- if os.path.exists(project_path):
132
- file_path = os.path.join(project_path, file_name)
133
- with open(file_path, "w") as file:
134
- file.write(code)
135
- st.session_state.workspace_projects[project_name]["files"].append(file_name)
136
- st.session_state.current_state['workspace_chat']['added_code'] = {"file_name": file_name, "code": code}
137
- commit_and_push_changes(f"Add code to {file_name} in project {project_name}")
138
- return f"Code added to {file_name} in project {project_name} successfully."
139
- else:
140
- return f"Project {project_name} does not exist."
141
-
142
- def terminal_interface(command, project_name=None):
143
- if project_name:
144
- project_path = os.path.join(PROJECT_ROOT, project_name)
145
- if not os.path.exists(project_path):
146
- return f"Project {project_name} does not exist."
147
- result = subprocess.run(command, cwd=project_path, shell=True, capture_output=True, text=True)
148
- else:
149
- result = subprocess.run(command, shell=True, capture_output=True, text=True)
150
- if result.returncode == 0:
151
- st.session_state.current_state['toolbox']['terminal_output'] = result.stdout
152
- return result.stdout
153
- else:
154
- st.session_state.current_state['toolbox']['terminal_output'] = result.stderr
155
- return result.stderr
156
-
157
- def summarize_text(text):
158
- summarizer = pipeline("summarization")
159
- summary = summarizer(text, max_length=50, min_length=25, do_sample=False)
160
- st.session_state.current_state['toolbox']['summary'] = summary[0]['summary_text']
161
- return summary[0]['summary_text']
162
-
163
- def sentiment_analysis(text):
164
- analyzer = pipeline("sentiment-analysis")
165
- sentiment = analyzer(text)
166
- st.session_state.current_state['toolbox']['sentiment'] = sentiment[0]
167
- return sentiment[0]
168
-
169
- # ... [rest of the translate_code function, but remove the OpenAI API call and replace it with your own logic] ...
170
-
171
- def generate_code(code_idea):
172
- # Replace this with a call to a Hugging Face model or your own logic
173
- # For example, using a text-generation pipeline:
174
- generator = pipeline('text-generation', model='gpt4o')
175
- generated_code = generator(code_idea, max_length=10000, num_return_sequences=1)[0]['generated_text']
176
- messages=[
177
- {"role": "system", "content": "You are an expert software developer."},
178
- {"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
179
- ]
180
- st.session_state.current_state['toolbox']['generated_code'] = generated_code
181
-
182
- return generated_code
183
-
184
- def translate_code(code, input_language, output_language):
185
- # Define a dictionary to map programming languages to their corresponding file extensions
186
- language_extensions = {
187
-
188
- }
189
 
190
- # Add code to handle edge cases such as invalid input and unsupported programming languages
191
- if input_language not in language_extensions:
192
- raise ValueError(f"Invalid input language: {input_language}")
193
- if output_language not in language_extensions:
194
- raise ValueError(f"Invalid output language: {output_language}")
195
-
196
- # Use the dictionary to map the input and output languages to their corresponding file extensions
197
- input_extension = language_extensions[input_language]
198
- output_extension = language_extensions[output_language]
199
-
200
- # Translate the code using the OpenAI API
201
- prompt = f"Translate this code from {input_language} to {output_language}:\n\n{code}"
202
- response = openai.ChatCompletion.create(
203
- model="gpt-4",
204
- messages=[
205
- {"role": "system", "content": "You are an expert software developer."},
206
- {"role": "user", "content": prompt}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  ]
208
- )
209
- translated_code = response.choices[0].message['content'].strip()
210
-
211
- # Return the translated code
212
- translated_code = response.choices[0].message['content'].strip()
213
- st.session_state.current_state['toolbox']['translated_code'] = translated_code
214
- return translated_code
215
-
216
- def generate_code(code_idea):
217
- response = openai.ChatCompletion.create(
218
- model="gpt-4",
219
- messages=[
220
- {"role": "system", "content": "You are an expert software developer."},
221
- {"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
222
  ]
223
- )
224
- generated_code = response.choices[0].message['content'].strip()
225
- st.session_state.current_state['toolbox']['generated_code'] = generated_code
226
- return generated_code
 
 
 
 
227
 
228
- def commit_and_push_changes(commit_message):
229
- """Commits and pushes changes to the Hugging Face repository."""
230
- commands = [
231
- "git add .",
232
- f"git commit -m '{commit_message}'",
233
- "git push"
234
- ]
235
- for command in commands:
236
- result = subprocess.run(command, shell=True, capture_output=True, text=True)
237
- if result.returncode != 0:
238
- st.error(f"Error executing command '{command}': {result.stderr}")
239
- break
240
 
241
- # Streamlit App
242
- st.title("AI Agent Creator")
243
-
244
- # Sidebar navigation
245
- st.sidebar.title("Navigation")
246
- app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
247
-
248
- if app_mode == "AI Agent Creator":
249
- # AI Agent Creator
250
- st.header("Create an AI Agent from Text")
251
-
252
- st.subheader("From Text")
253
- agent_name = st.text_input("Enter agent name:")
254
- text_input = st.text_area("Enter skills (one per line):")
255
- if st.button("Create Agent"):
256
- agent_prompt = create_agent_from_text(agent_name, text_input)
257
- st.success(f"Agent '{agent_name}' created and saved successfully.")
258
- st.session_state.available_agents.append(agent_name)
259
-
260
- elif app_mode == "Tool Box":
261
- # Tool Box
262
- st.header("AI-Powered Tools")
263
-
264
- # Chat Interface
265
- st.subheader("Chat with CodeCraft")
266
- chat_input = st.text_area("Enter your message:")
267
- if st.button("Send"):
268
- if chat_input.startswith("@"):
269
- agent_name = chat_input.split(" ")[0][1:] # Extract agent_name from @agent_name
270
- chat_input = " ".join(chat_input.split(" ")[1:]) # Remove agent_name from input
271
- chat_response = chat_interface_with_agent(chat_input, agent_name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  else:
273
- chat_response = chat_interface(chat_input)
274
- st.session_state.chat_history.append((chat_input, chat_response))
275
- st.write(f"CodeCraft: {chat_response}")
276
-
277
- # Terminal Interface
278
- st.subheader("Terminal")
279
- terminal_input = st.text_input("Enter a command:")
280
- if st.button("Run"):
281
- terminal_output = terminal_interface(terminal_input)
282
- st.session_state.terminal_history.append((terminal_input, terminal_output))
283
- st.code(terminal_output, language="bash")
284
-
285
- # Code Editor Interface
286
- st.subheader("Code Editor")
287
- code_editor = st.text_area("Write your code:", height=300)
288
- if st.button("Format & Lint"):
289
- formatted_code, lint_message = code_editor_interface(code_editor)
290
- st.code(formatted_code, language="python")
291
- st.info(lint_message)
292
-
293
- # Text Summarization Tool
294
- st.subheader("Summarize Text")
295
- text_to_summarize = st.text_area("Enter text to summarize:")
296
- if st.button("Summarize"):
297
- summary = summarize_text(text_to_summarize)
298
- st.write(f"Summary: {summary}")
299
-
300
- # Sentiment Analysis Tool
301
- st.subheader("Sentiment Analysis")
302
- sentiment_text = st.text_area("Enter text for sentiment analysis:")
303
- if st.button("Analyze Sentiment"):
304
- sentiment = sentiment_analysis(sentiment_text)
305
- st.write(f"Sentiment: {sentiment}")
306
-
307
- # Text Translation Tool (Code Translation)
308
- st.subheader("Translate Code")
309
- code_to_translate = st.text_area("Enter code to translate:")
310
- source_language = st.text_input("Enter source language (e.g. 'Python'):")
311
- target_language = st.text_input("Enter target language (e.g. 'JavaScript'):")
312
- if st.button("Translate Code"):
313
- translated_code = translate_code(code_to_translate, source_language, target_language)
314
- st.code(translated_code, language=target_language.lower())
315
-
316
- # Code Generation
317
- st.subheader("Code Generation")
318
- code_idea = st.text_input("Enter your code idea:")
319
- if st.button("Generate Code"):
320
- generated_code = generate_code(code_idea)
321
- st.code(generated_code, language="python")
322
-
323
- # Display Preset Commands
324
- st.subheader("Preset Commands")
325
- preset_commands = {
326
- "Create a new project": "create_project('project_name')",
327
- "Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')",
328
- "Run terminal command": "terminal_interface('command', 'project_name')",
329
- "Generate code": "generate_code('code_idea')",
330
- "Summarize text": "summarize_text('text')",
331
- "Analyze sentiment": "sentiment_analysis('text')",
332
- "Translate code": "translate_code('code', 'source_language', 'target_language')",
333
- }
334
- for command_name, command in preset_commands.items():
335
- st.write(f"{command_name}: `{command}`")
336
-
337
- elif app_mode == "Workspace Chat App":
338
- # Workspace Chat App
339
- st.header("Workspace Chat App")
340
-
341
- # Project Workspace Creation
342
- st.subheader("Create a New Project")
343
- project_name = st.text_input("Enter project name:")
344
- if st.button("Create Project"):
345
- workspace_status = workspace_interface(project_name)
346
- st.success(workspace_status)
347
-
348
- # Add Code to Workspace
349
- st.subheader("Add Code to Workspace")
350
- code_to_add = st.text_area("Enter code to add to workspace:")
351
- file_name = st.text_input("Enter file name (e.g. 'app.py'):")
352
- if st.button("Add Code"):
353
- add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
354
- st.success(add_code_status)
355
-
356
- # Terminal Interface with Project Context
357
- st.subheader("Terminal (Workspace Context)")
358
- terminal_input = st.text_input("Enter a command within the workspace:")
359
- if st.button("Run Command"):
360
- terminal_output = terminal_interface(terminal_input, project_name)
361
- st.code(terminal_output, language="bash")
362
-
363
- # Chat Interface for Guidance
364
- st.subheader("Chat with CodeCraft for Guidance")
365
- chat_input = st.text_area("Enter your message for guidance:")
366
- if st.button("Get Guidance"):
367
- chat_response = chat_interface(chat_input)
368
- st.session_state.chat_history.append((chat_input, chat_response))
369
- st.write(f"CodeCraft: {chat_response}")
370
-
371
- # Display Chat History
372
- st.subheader("Chat History")
373
- for user_input, response in st.session_state.chat_history:
374
- st.write(f"User: {user_input}")
375
- st.write(f"CodeCraft: {response}")
376
-
377
- # Display Terminal History
378
- st.subheader("Terminal History")
379
- for command, output in st.session_state.terminal_history:
380
- st.write(f"Command: {command}")
381
- st.code(output, language="bash")
382
-
383
- # Display Projects and Files
384
- st.subheader("Workspace Projects")
385
- for project, details in st.session_state.workspace_projects.items():
386
- st.write(f"Project: {project}")
387
- for file in details['files']:
388
- st.write(f" - {file}")
389
-
390
- # Chat with AI Agents
391
- st.subheader("Chat with AI Agents")
392
- selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
393
- agent_chat_input = st.text_area("Enter your message for the agent:")
394
- if st.button("Send to Agent"):
395
- agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
396
- st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
397
- st.write(f"{selected_agent}: {agent_chat_response}")
398
-
399
- # Automate Build Process
400
- st.subheader("Automate Build Process")
401
- if st.button("Automate"):
402
- agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
403
- summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
404
- st.write("Autonomous Build Summary:")
405
- st.write(summary)
406
- st.write("Next Step:")
407
- st.write(next_step)
408
-
409
- # Display current state for debugging
410
- st.sidebar.subheader("Current State")
411
- st.sidebar.json(st.session_state.current_state)
 
2
  import subprocess
3
  import streamlit as st
4
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
5
+ from langchain_community.llms import HuggingFaceHub
6
+ from langchain_community.embeddings import HuggingFaceHubEmbeddings
7
+ from langchain_community.document_loaders import PyPDFLoader
8
+ from langchain_community.vectorstores import FAISS
9
+ from langchain.chains import ConversationalRetrievalChain
10
+ from langchain.chains.question_answering import load_qa_chain
11
+ from llama_cpp import Llama, LlamaCppPythonProvider, LlamaCppAgent
12
+ from llama_cpp.llama_cpp_agent import get_messages_formatter_type, get_context_by_model
13
  from io import StringIO
14
+ import tempfile
15
+
16
+ # --- Global Variables ---
17
+ CURRENT_PROJECT = {} # Store project data (code, packages, etc.)
18
+ MODEL_OPTIONS = {
19
+ "CodeQwen": "Qwen/CodeQwen1.5-7B-Chat-GGUF",
20
+ "Codestral": "bartowski/Codestral-22B-v0.1-GGUF",
21
+ "AutoCoder": "bartowski/AutoCoder-GGUF",
22
+ }
23
+ MODEL_FILENAMES = {
24
+ "CodeQwen": "codeqwen-1_5-7b-chat-q6_k.gguf",
25
+ "Codestral": "Codestral-22B-v0.1-Q6_K.gguf",
26
+ "AutoCoder": "AutoCoder-Q6_K.gguf",
27
+ }
28
  HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
29
  PROJECT_ROOT = "projects"
30
  AGENT_DIRECTORY = "agents"
 
44
  'workspace_chat': {}
45
  }
46
 
47
+ # --- Load NLP Pipelines ---
48
+ classifier = pipeline("text-classification", model="facebook/bart-large-mnli")
49
+
50
+ # --- Load the model and tokenizer ---
51
+ model = AutoModelForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1", use_auth_token=os.environ.get("huggingface_token"))
52
+ tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1", use_auth_token=os.environ.get("huggingface_token"))
53
+
54
+ # --- Utility Functions ---
55
+ def install_and_import(package_name):
56
+ """Installs a package using pip and imports it."""
57
+ subprocess.check_call(["pip", "install", package_name])
58
+ return importlib.import_module(package_name)
59
+
60
+ def extract_package_name(input_str):
61
+ """Extracts the package name from a PyPI URL or pip command."""
62
+ if input_str.startswith("https://pypi.org/project/"):
63
+ return input_str.split("/")[-2]
64
+ elif input_str.startswith("pip install "):
65
+ return input_str.split(" ")[2]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  else:
67
+ return input_str
68
+
69
+ def create_interface_from_input(input_str):
70
+ """Creates a Gradio interface with buttons for functions from a package."""
 
 
 
 
 
 
 
 
 
 
 
 
71
  try:
72
+ package_name = extract_package_name(input_str)
73
+ module = install_and_import(package_name)
74
+
75
+ # Handle Flask application context if needed
76
+ if 'flask' in sys.modules or 'flask_restful' in sys.modules:
77
+ app = Flask(__name__)
78
+ with app.app_context():
79
+ functions = [getattr(module, name) for name in dir(module) if callable(getattr(module, name))]
80
+ else:
81
+ functions = [getattr(module, name) for name in dir(module) if callable(getattr(module, name))]
82
+
83
+ function_list = [(func.__name__, func) for func in functions if not func.__name__.startswith("_")]
84
+ return function_list, f"Interface for `{package_name}` created."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
+ except Exception as e:
87
+ return [], str(e)
88
+
89
+ def execute_pip_command(command, add_message):
90
+ """Executes a pip command and streams the output."""
91
+ process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
92
+ while True:
93
+ output = process.stdout.readline()
94
+ if output == '' and process.poll() is not None:
95
+ break
96
+ if output:
97
+ add_message("System", f"
98
+
99
+
100
+ \n{output.strip()}\n
101
+
102
+ time.sleep(0.1) # Simulate delay for more realistic streaming
103
+ rc = process.poll()
104
+ return rc
105
+
106
+ def generate_text(input_text):
107
+ """Generates text using the loaded language model."""
108
+ inputs = tokenizer(input_text, return_tensors="pt")
109
+ output = model.generate(**inputs, max_length=500, num_return_sequences=1)
110
+ return tokenizer.decode(output[0], skip_special_tokens=True)
111
+
112
+ # --- AI Agent Functions ---
113
+ def analyze_user_intent(user_input):
114
+ """Classifies the user's intent based on their input."""
115
+ classification = classifier(user_input)
116
+ return classification[0]['label']
117
+
118
+ def generate_mini_app_ideas(theme):
119
+ """Generates mini-app ideas based on the user's theme."""
120
+ if theme.lower() == "productivity":
121
+ return [
122
+ "Idea-to-Codebase Generator",
123
+ "Automated GitHub Repo Manager",
124
+ "AI-Powered IDE"
125
  ]
126
+ elif theme.lower() == "creativity":
127
+ return [
128
+ "Brainstorming Assistant",
129
+ "Mood Board Generator",
130
+ "Writing Assistant"
 
 
 
 
 
 
 
 
 
131
  ]
132
+ elif theme.lower() == "well-being":
133
+ return [
134
+ "Meditation Guide",
135
+ "Mood Tracker",
136
+ "Sleep Tracker"
137
+ ]
138
+ else:
139
+ return ["No matching mini-apps found. Try a different theme."]
140
 
141
+ def generate_app_code(app_name, app_description, model_name, history):
142
+ """Generates code for the selected mini-app using the specified GGUF model."""
143
+ prompt = f"Write a Python script for a {app_description} named {app_name} using Gradio and Streamlit:"
144
+ agent = get_agent(model_name)
145
+ generated_code = agent.chat(prompt, history)
146
+ return generated_code
 
 
 
 
 
 
147
 
148
+ def execute_terminal_command(command):
149
+ """Executes a terminal command and returns the output."""
150
+ try:
151
+ result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, universal_newlines=True)
152
+ return result.strip(), None
153
+ except subprocess.CalledProcessError as e:
154
+ return e.output.strip(), str(e)
155
+
156
+ def install_package(package_name):
157
+ """Installs a package using pip."""
158
+ output, error = execute_terminal_command(f"pip install {package_name}")
159
+ if error:
160
+ return f"Error installing package: {error}"
161
+ else:
162
+ return f"Package `{package_name}` installed successfully."
163
+
164
+ def get_project_data():
165
+ """Returns the current project data."""
166
+ return CURRENT_PROJECT
167
+
168
+ def update_project_data(key, value):
169
+ """Updates the project data."""
170
+ CURRENT_PROJECT[key] = value
171
+
172
+ def handle_chat(input_text, history):
173
+ """Handles user input in the chat interface."""
174
+ def add_message(sender, message):
175
+ history.append((sender, message))
176
+
177
+ add_message("User", input_text)
178
+
179
+ if input_text.startswith("pip install ") or input_text.startswith("https://pypi.org/project/"):
180
+ package_name = extract_package_name(input_text)
181
+ add_message("System", f"Installing `{package_name}`...")
182
+ result = install_package(package_name)
183
+ add_message("System", result)
184
+ update_project_data("packages", CURRENT_PROJECT.get("packages", []) + [package_name])
185
+ return history, dynamic_functions
186
+
187
+ # --- AI Agent Interaction ---
188
+ if USER_INTENT is None:
189
+ add_message("System", analyze_user_intent(input_text))
190
+ add_message("System", "What kind of mini-app do you have in mind?")
191
+ elif not MINI_APPS:
192
+ add_message("System", "Here are some ideas:")
193
+ for idea in generate_mini_app_ideas(input_text):
194
+ add_message("System", f"- {idea}")
195
+ add_message("System", "Which one would you like to build?")
196
+ elif CURRENT_APP["name"] is None:
197
+ selected_app = input_text
198
+ app_description = next((app for app in MINI_APPS if selected_app in app), None)
199
+ if app_description:
200
+ add_message("System", f"Generating code for {app_description}...")
201
+ code = generate_app_code(selected_app, app_description, "CodeQwen", history) # Use CodeQwen by default
202
+ add_message("System", f"
203
+
204
+
205
+ python\n{code}\n
206
+
207
+ add_message("System", "Code generated! What else can I do for you?")
208
+ update_project_data("code", code)
209
+ update_project_data("app_name", selected_app)
210
+ update_project_data("app_description", app_description)
211
  else:
212
+ add_message("System", "Please choose from the provided mini-app ideas.")
213
+ else:
214
+ add_message("System", "You already have an app in progress. Do you want to start over?")
215
+
216
+ return history, dynamic_functions
217
+
218
+ # --- Prebuilt Tools ---
219
+ def generate_code_tool(input_text, history):
220
+ """Prebuilt tool for code generation."""
221
+ code = generate_app_code("MyTool", "A tool to do something", "CodeQwen", history) # Use CodeQwen by default
222
+ return f"
223
+
224
+
225
+ python\n{code}\n
226
+
227
+ def analyze_code_tool(input_text, history):
228
+ """Prebuilt tool for code analysis."""
229
+ agent = get_agent("Codestral")
230
+ analysis = agent.chat(input_text, history)
231
+ return analysis
232
+
233
+ # --- Streamlit Interface ---
234
+ st.title("AI4ME: Your Personal AI App Workshop")
235
+ st.markdown("## Let's build your dream app together! 🤖")
236
+
237
+ # --- Hugging Face Token Input ---
238
+ huggingface_token = st.text_input("Enter your Hugging Face Token", type="password", key="huggingface_token")
239
+ os.environ["huggingface_token"] = huggingface_token
240
+
241
+ # --- Chat Interface ---
242
+ chat_history = []
243
+ chat_input = st.text_input("Tell me your idea...", key="chat_input")
244
+ if chat_input:
245
+ chat_history, dynamic_functions = handle_chat(chat_input, chat_history)
246
+ for sender, message in chat_history:
247
+ st.markdown(f"**{sender}:** {message}")
248
+
249
+ # --- Code Execution and Deployment ---
250
+ if CURRENT_APP["code"]:
251
+ st.markdown("## Your App Code:")
252
+ code_area = st.text_area("Your App Code", value=CURRENT_APP["code"], key="code_area")
253
+
254
+ st.markdown("## Deploy Your App (Coming Soon!)")
255
+ # Add deployment functionality here using Streamlit's deployment features.
256
+ # For example, you could use Streamlit's `st.button` to trigger deployment.
257
+
258
+ # --- Code Execution ---
259
+ st.markdown("## Run Your App:")
260
+ if st.button("Execute Code"):
261
+ try:
262
+ # Use Hugging Face's text-generation pipeline for code execution
263
+ inputs = tokenizer(code_area, return_tensors="pt")
264
+ output = model.generate(**inputs, max_length=500, num_return_sequences=1)
265
+ output = tokenizer.decode(output[0], skip_special_tokens=True)
266
+ st.success(f"Code executed successfully!\n{output}")
267
+ except Exception as e:
268
+ st.error(f"Error executing code: {e}")
269
+
270
+ # --- Code Editing ---
271
+ st.markdown("## Edit Your Code:")
272
+ if st.button("Edit Code"):
273
+ try:
274
+ # Use Hugging Face's text-generation pipeline for code editing
275
+ prompt = f"Improve the following Python code:\n
276
+
277
+
278
+ python\n{code_area}\n
279
+
280
+ inputs = tokenizer(prompt, return_tensors="pt")
281
+ output = model.generate(**inputs, max_length=500, num_return_sequences=1)
282
+ edited_code = tokenizer.decode(output[0], skip_special_tokens=True).split("
283
+
284
+
285
+ python\n")[1].split("\n
286
+
287
+ st.success(f"Code edited successfully!\n{edited_code}")
288
+ update_project_data("code", edited_code)
289
+ code_area.value = edited_code
290
+ except Exception as e:
291
+ st.error(f"Error editing code: {e}")
292
+
293
+ # --- Prebuilt Tools ---
294
+ st.markdown("## Prebuilt Tools:")
295
+ with st.expander("Generate Code"):
296
+ code_input = st.text_area("Enter your code request:", key="code_input")
297
+ if st.button("Generate"):
298
+ code_output = generate_code_tool(code_input, chat_history)
299
+ st.markdown(code_output)
300
+
301
+ with st.expander("Analyze Code"):
302
+ code_input = st.text_area("Enter your code:", key="analyze_code_input")
303
+ if st.button("Analyze"):
304
+ analysis_output = analyze_code_tool(code_input, chat_history)
305
+ st.markdown(analysis_output)
306
+
307
+ # --- Additional Features ---
308
+ # Add features like:
309
+ # - Code editing
310
+ # - Integration with external APIs
311
+ # - Advanced AI agents for more complex tasks
312
+ # - User account management