acecalisto3 commited on
Commit
92fe1ec
·
verified ·
1 Parent(s): 37e4067

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +406 -155
app.py CHANGED
@@ -1,166 +1,417 @@
1
  import os
2
  import sys
3
- import time
4
- import tempfile
5
- import hashlib
6
- import asyncio
7
- import autopep8
8
- from functools import lru_cache
9
- from multiprocessing import Pool
10
- from tenacity import retry, stop_after_attempt, wait_exponential
11
-
12
- import huggingface_hub
13
- import transformers
14
- import gradio as gr
15
- from huggingface_hub import HfFolder
16
-
17
- # Caching Generated Code
18
- code_cache = {}
19
-
20
- def generate_code(idea):
21
- idea_hash = hashlib.md5(idea.encode()).hexdigest()
22
- if idea_hash in code_cache:
23
- return code_cache[idea_hash]
24
- code = gemmacode.generate(idea)
25
- code_cache[idea_hash] = code
26
- return code
27
-
28
- # Parallel Processing
29
- def generate_code_parallel(ideas):
30
- with Pool() as pool:
31
- return pool.map(gemmacode.generate, ideas)
32
-
33
- # Asynchronous Code Generation
34
- async def generate_code_async(idea):
35
- return await gemmacode.generate_async(idea)
36
-
37
- # Batching Requests
38
- def batch_generate(ideas, batch_size=10):
39
- for i in range(0, len(ideas), batch_size):
40
- batch = ideas[i:i+batch_size]
41
- yield gemmacode.generate_batch(batch)
42
-
43
- # Progressive Code Generation
44
- def generate_progressive(idea):
45
- for partial_code in gemmacode.generate_stream(idea):
46
- yield partial_code
47
- # Process or display partial_code
48
-
49
- # Optimizing Model Loading
50
- model = None
51
-
52
- def get_model():
53
- global model
54
- if model is None:
55
- model = gemmacode.load_model()
56
- return model
57
-
58
- def generate_code_optimized(idea):
59
- return get_model().generate(idea)
60
-
61
- # Error Handling and Retries
62
- @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
63
- def generate_code_with_retry(idea):
64
- return gemmacode.generate(idea)
65
-
66
- # Code Optimization Post-Generation
67
- def optimize_generated_code(code):
68
- return autopep8.fix_code(code)
69
-
70
- # Lazy Evaluation
71
- @lru_cache(maxsize=None)
72
- def lazy_generate_code(idea):
73
- return gemmacode.generate(idea)
74
-
75
- async def main():
76
- try:
77
- # Get the user's idea
78
- idea = input("What is your idea for an application? ")
79
- except EOFError:
80
- print("No input received. Exiting the program.")
81
- return
82
 
83
- # Generate the code for the application using optimized methods
84
- code = await generate_code_async(idea)
85
- code = optimize_generated_code(code)
86
 
87
- # Test the code
88
- try:
89
- transformers.pipeline("text-generation")(code)
90
- except Exception as e:
91
- print("The code failed to run:", e)
92
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- # Ensure the functionality of the application
 
95
  try:
96
- gr.Interface(fn=transformers.pipeline("text-generation"), inputs=gr.Textbox(), outputs=gr.Textbox()).launch()
97
- except Exception as e:
98
- print("The application failed to run:", e)
99
- return
 
100
 
101
- # Provide an embedded webapp demo of the user's idea implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  try:
103
- hf_folder = HfFolder(path=tempfile.mkdtemp())
104
- hf_folder.save(code)
105
- hf_folder.push_to_hub(repo_id="acecalisto3/gemmacode-demo", commit_message="Initial commit")
106
- print(f"The demo is available at: https://huggingface.co/acecalisto3/gemmacode-demo")
107
- except Exception as e:
108
- print("The demo failed to launch:", e)
109
- return
110
-
111
- # Offer the option to rebuild or deploy
112
- while True:
113
- try:
114
- choice = input("Do you want to rebuild or deploy the application? (r/d/q) ")
115
- except EOFError:
116
- print("No input received. Exiting the program.")
117
- return
118
-
119
- if choice == "r":
120
- # Rebuild the code using optimized methods
121
- code = await generate_code_async(idea)
122
- code = optimize_generated_code(code)
123
-
124
- # Test the code
125
- try:
126
- transformers.pipeline("text-generation")(code)
127
- except Exception as e:
128
- print("The code failed to run:", e)
129
- return
130
-
131
- # Ensure the functionality of the application
132
- try:
133
- gr.Interface(fn=transformers.pipeline("text-generation"), inputs=gr.Textbox(), outputs=gr.Textbox()).launch()
134
- except Exception as e:
135
- print("The application failed to run:", e)
136
- return
137
-
138
- # Provide an embedded webapp demo of the user's idea implementation
139
- try:
140
- hf_folder = HfFolder(path=tempfile.mkdtemp())
141
- hf_folder.save(code)
142
- hf_folder.push_to_hub(repo_id="acecalisto3/gemmacode-demo", commit_message="Initial commit")
143
- print(f"The demo is available at: https://huggingface.co/acecalisto3/gemmacode-demo")
144
- except Exception as e:
145
- print("The demo failed to launch:", e)
146
- return
147
- elif choice == "d":
148
- # Deploy the application
149
- try:
150
- api_token = os.environ["HF_TOKEN"]
151
- hub = huggingface_hub.HfApi(api_token=api_token)
152
- hub.create_repo(name="my-app", organization="my-org")
153
- hf_folder = HfFolder(path=tempfile.mkdtemp())
154
- hf_folder.save(code)
155
- hf_folder.push_to_hub(repo_id="my-org/my-app", commit_message="Initial commit")
156
- print("The application has been deployed to: https://huggingface.co/my-org/my-app")
157
- except Exception as e:
158
- print("The application failed to deploy:", e)
159
- return
160
- elif choice == "q":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  else:
163
- print("Invalid choice")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
- if __name__ == "__main__":
166
- asyncio.run(main())
 
1
  import os
2
  import sys
3
+ import subprocess
4
+ import streamlit as st
5
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
6
+ import black
7
+ from pylint import lint
8
+ from io import StringIO
9
+ import openai
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # Set your OpenAI API key here
12
+ openai.api_key = "YOUR_OPENAI_API_KEY"
 
13
 
14
+ HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
15
+ PROJECT_ROOT = "projects"
16
+ AGENT_DIRECTORY = "agents"
17
+
18
+ # Global state to manage communication between Tool Box and Workspace Chat App
19
+ if 'chat_history' not in st.session_state:
20
+ st.session_state.chat_history = []
21
+ if 'terminal_history' not in st.session_state:
22
+ st.session_state.terminal_history = []
23
+ if 'workspace_projects' not in st.session_state:
24
+ st.session_state.workspace_projects = {}
25
+ if 'available_agents' not in st.session_state:
26
+ st.session_state.available_agents = []
27
+ if 'current_state' not in st.session_state:
28
+ st.session_state.current_state = {
29
+ 'toolbox': {},
30
+ 'workspace_chat': {}
31
+ }
32
+
33
+ class AIAgent:
34
+ def __init__(self, name, description, skills):
35
+ self.name = name
36
+ self.description = description
37
+ self.skills = skills
38
+
39
+ def create_agent_prompt(self):
40
+ skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
41
+ agent_prompt = f"""
42
+ As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
43
+ {skills_str}
44
+ 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.
45
+ """
46
+ return agent_prompt
47
+
48
+ def autonomous_build(self, chat_history, workspace_projects):
49
+ """
50
+ Autonomous build logic that continues based on the state of chat history and workspace projects.
51
+ """
52
+ summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
53
+ summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
54
+
55
+ next_step = "Based on the current state, the next logical step is to implement the main application logic."
56
+
57
+ return summary, next_step
58
+
59
+ def save_agent_to_file(agent):
60
+ """Saves the agent's prompt to a file locally and then commits to the Hugging Face repository."""
61
+ if not os.path.exists(AGENT_DIRECTORY):
62
+ os.makedirs(AGENT_DIRECTORY)
63
+ file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
64
+ config_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}Config.txt")
65
+ with open(file_path, "w") as file:
66
+ file.write(agent.create_agent_prompt())
67
+ with open(config_path, "w") as file:
68
+ file.write(f"Agent Name: {agent.name}\nDescription: {agent.description}")
69
+ st.session_state.available_agents.append(agent.name)
70
+
71
+ commit_and_push_changes(f"Add agent {agent.name}")
72
+
73
+ def load_agent_prompt(agent_name):
74
+ """Loads an agent prompt from a file."""
75
+ file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
76
+ if os.path.exists(file_path):
77
+ with open(file_path, "r") as file:
78
+ agent_prompt = file.read()
79
+ return agent_prompt
80
+ else:
81
+ return None
82
+
83
+ def create_agent_from_text(name, text):
84
+ skills = text.split('\n')
85
+ agent = AIAgent(name, "AI agent created from text input.", skills)
86
+ save_agent_to_file(agent)
87
+ return agent.create_agent_prompt()
88
+
89
+ # Chat interface using a selected agent
90
+ def chat_interface_with_agent(input_text, agent_name):
91
+ agent_prompt = load_agent_prompt(agent_name)
92
+ if agent_prompt is None:
93
+ return f"Agent {agent_name} not found."
94
 
95
+ # Load the GPT-2 model which is compatible with AutoModelForCausalLM
96
+ model_name = "gpt2"
97
  try:
98
+ model = AutoModelForCausalLM.from_pretrained(model_name)
99
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
100
+ generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
101
+ except EnvironmentError as e:
102
+ return f"Error loading model: {e}"
103
 
104
+ # Combine the agent prompt with user input
105
+ combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
106
+
107
+ # Truncate input text to avoid exceeding the model's maximum length
108
+ max_input_length = 900
109
+ input_ids = tokenizer.encode(combined_input, return_tensors="pt")
110
+ if input_ids.shape[1] > max_input_length:
111
+ input_ids = input_ids[:, :max_input_length]
112
+
113
+ # Generate chatbot response
114
+ outputs = model.generate(
115
+ 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
116
+ )
117
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
118
+ return response
119
+
120
+ def workspace_interface(project_name):
121
+ project_path = os.path.join(PROJECT_ROOT, project_name)
122
+ if not os.path.exists(PROJECT_ROOT):
123
+ os.makedirs(PROJECT_ROOT)
124
+ if not os.path.exists(project_path):
125
+ os.makedirs(project_path)
126
+ st.session_state.workspace_projects[project_name] = {"files": []}
127
+ st.session_state.current_state['workspace_chat']['project_name'] = project_name
128
+ commit_and_push_changes(f"Create project {project_name}")
129
+ return f"Project {project_name} created successfully."
130
+ else:
131
+ return f"Project {project_name} already exists."
132
+
133
+ def add_code_to_workspace(project_name, code, file_name):
134
+ project_path = os.path.join(PROJECT_ROOT, project_name)
135
+ if os.path.exists(project_path):
136
+ file_path = os.path.join(project_path, file_name)
137
+ with open(file_path, "w") as file:
138
+ file.write(code)
139
+ st.session_state.workspace_projects[project_name]["files"].append(file_name)
140
+ st.session_state.current_state['workspace_chat']['added_code'] = {"file_name": file_name, "code": code}
141
+ commit_and_push_changes(f"Add code to {file_name} in project {project_name}")
142
+ return f"Code added to {file_name} in project {project_name} successfully."
143
+ else:
144
+ return f"Project {project_name} does not exist."
145
+
146
+ def terminal_interface(command, project_name=None):
147
+ if project_name:
148
+ project_path = os.path.join(PROJECT_ROOT, project_name)
149
+ if not os.path.exists(project_path):
150
+ return f"Project {project_name} does not exist."
151
+ result = subprocess.run(command, cwd=project_path, shell=True, capture_output=True, text=True)
152
+ else:
153
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
154
+ if result.returncode == 0:
155
+ st.session_state.current_state['toolbox']['terminal_output'] = result.stdout
156
+ return result.stdout
157
+ else:
158
+ st.session_state.current_state['toolbox']['terminal_output'] = result.stderr
159
+ return result.stderr
160
+
161
+ def code_editor_interface(code):
162
  try:
163
+ formatted_code = black.format_str(code, mode=black.FileMode())
164
+ except black.NothingChanged:
165
+ formatted_code = code
166
+ result = StringIO()
167
+ sys.stdout = result
168
+ sys.stderr = result
169
+ (pylint_stdout, pylint_stderr) = lint.py_run(code, return_std=True)
170
+ sys.stdout = sys.__stdout__
171
+ sys.stderr = sys.__stderr__
172
+ lint_message = pylint_stdout.getvalue() + pylint_stderr.getvalue()
173
+ st.session_state.current_state['toolbox']['formatted_code'] = formatted_code
174
+ st.session_state.current_state['toolbox']['lint_message'] = lint_message
175
+ return formatted_code, lint_message
176
+
177
+ def summarize_text(text):
178
+ summarizer = pipeline("summarization")
179
+ summary = summarizer(text, max_length=50, min_length=25, do_sample=False)
180
+ st.session_state.current_state['toolbox']['summary'] = summary[0]['summary_text']
181
+ return summary[0]['summary_text']
182
+
183
+ def sentiment_analysis(text):
184
+ analyzer = pipeline("sentiment-analysis")
185
+ sentiment = analyzer(text)
186
+ st.session_state.current_state['toolbox']['sentiment'] = sentiment[0]
187
+ return sentiment[0]
188
+
189
+ def translate_code(code, input_language, output_language):
190
+ # Define a dictionary to map programming languages to their corresponding file extensions
191
+ language_extensions = {
192
+ # ignore the specific languages right now, and continue to EOF
193
+ }
194
+
195
+ # Add code to handle edge cases such as invalid input and unsupported programming languages
196
+ if input_language not in language_extensions:
197
+ raise ValueError(f"Invalid input language: {input_language}")
198
+ if output_language not in language_extensions:
199
+ raise ValueError(f"Invalid output language: {output_language}")
200
+
201
+ # Use the dictionary to map the input and output languages to their corresponding file extensions
202
+ input_extension = language_extensions[input_language]
203
+ output_extension = language_extensions[output_language]
204
+
205
+ # Translate the code using the OpenAI API
206
+ prompt = f"Translate this code from {input_language} to {output_language}:\n\n{code}"
207
+ response = openai.ChatCompletion.create(
208
+ model="gpt-4",
209
+ messages=[
210
+ {"role": "system", "content": "You are an expert software developer."},
211
+ {"role": "user", "content": prompt}
212
+ ]
213
+ )
214
+ translated_code = response.choices[0].message['content'].strip()
215
+
216
+ # Return the translated code
217
+ translated_code = response.choices[0].message['content'].strip()
218
+ st.session_state.current_state['toolbox']['translated_code'] = translated_code
219
+ return translated_code
220
+
221
+ def generate_code(code_idea):
222
+ response = openai.ChatCompletion.create(
223
+ model="gpt-4",
224
+ messages=[
225
+ {"role": "system", "content": "You are an expert software developer."},
226
+ {"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
227
+ ]
228
+ )
229
+ generated_code = response.choices[0].message['content'].strip()
230
+ st.session_state.current_state['toolbox']['generated_code'] = generated_code
231
+ return generated_code
232
+
233
+ def commit_and_push_changes(commit_message):
234
+ """Commits and pushes changes to the Hugging Face repository."""
235
+ commands = [
236
+ "git add .",
237
+ f"git commit -m '{commit_message}'",
238
+ "git push"
239
+ ]
240
+ for command in commands:
241
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
242
+ if result.returncode != 0:
243
+ st.error(f"Error executing command '{command}': {result.stderr}")
244
  break
245
+
246
+ # Streamlit App
247
+ st.title("AI Agent Creator")
248
+
249
+ # Sidebar navigation
250
+ st.sidebar.title("Navigation")
251
+ app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
252
+
253
+ if app_mode == "AI Agent Creator":
254
+ # AI Agent Creator
255
+ st.header("Create an AI Agent from Text")
256
+
257
+ st.subheader("From Text")
258
+ agent_name = st.text_input("Enter agent name:")
259
+ text_input = st.text_area("Enter skills (one per line):")
260
+ if st.button("Create Agent"):
261
+ agent_prompt = create_agent_from_text(agent_name, text_input)
262
+ st.success(f"Agent '{agent_name}' created and saved successfully.")
263
+ st.session_state.available_agents.append(agent_name)
264
+
265
+ elif app_mode == "Tool Box":
266
+ # Tool Box
267
+ st.header("AI-Powered Tools")
268
+
269
+ # Chat Interface
270
+ st.subheader("Chat with CodeCraft")
271
+ chat_input = st.text_area("Enter your message:")
272
+ if st.button("Send"):
273
+ if chat_input.startswith("@"):
274
+ agent_name = chat_input.split(" ")[0][1:] # Extract agent_name from @agent_name
275
+ chat_input = " ".join(chat_input.split(" ")[1:]) # Remove agent_name from input
276
+ chat_response = chat_interface_with_agent(chat_input, agent_name)
277
  else:
278
+ chat_response = chat_interface(chat_input)
279
+ st.session_state.chat_history.append((chat_input, chat_response))
280
+ st.write(f"CodeCraft: {chat_response}")
281
+
282
+ # Terminal Interface
283
+ st.subheader("Terminal")
284
+ terminal_input = st.text_input("Enter a command:")
285
+ if st.button("Run"):
286
+ terminal_output = terminal_interface(terminal_input)
287
+ st.session_state.terminal_history.append((terminal_input, terminal_output))
288
+ st.code(terminal_output, language="bash")
289
+
290
+ # Code Editor Interface
291
+ st.subheader("Code Editor")
292
+ code_editor = st.text_area("Write your code:", height=300)
293
+ if st.button("Format & Lint"):
294
+ formatted_code, lint_message = code_editor_interface(code_editor)
295
+ st.code(formatted_code, language="python")
296
+ st.info(lint_message)
297
+
298
+ # Text Summarization Tool
299
+ st.subheader("Summarize Text")
300
+ text_to_summarize = st.text_area("Enter text to summarize:")
301
+ if st.button("Summarize"):
302
+ summary = summarize_text(text_to_summarize)
303
+ st.write(f"Summary: {summary}")
304
+
305
+ # Sentiment Analysis Tool
306
+ st.subheader("Sentiment Analysis")
307
+ sentiment_text = st.text_area("Enter text for sentiment analysis:")
308
+ if st.button("Analyze Sentiment"):
309
+ sentiment = sentiment_analysis(sentiment_text)
310
+ st.write(f"Sentiment: {sentiment}")
311
+
312
+ # Text Translation Tool (Code Translation)
313
+ st.subheader("Translate Code")
314
+ code_to_translate = st.text_area("Enter code to translate:")
315
+ source_language = st.text_input("Enter source language (e.g. 'Python'):")
316
+ target_language = st.text_input("Enter target language (e.g. 'JavaScript'):")
317
+ if st.button("Translate Code"):
318
+ translated_code = translate_code(code_to_translate, source_language, target_language)
319
+ st.code(translated_code, language=target_language.lower())
320
+
321
+ # Code Generation
322
+ st.subheader("Code Generation")
323
+ code_idea = st.text_input("Enter your code idea:")
324
+ if st.button("Generate Code"):
325
+ generated_code = generate_code(code_idea)
326
+ st.code(generated_code, language="python")
327
+
328
+ # Display Preset Commands
329
+ st.subheader("Preset Commands")
330
+ preset_commands = {
331
+ "Create a new project": "create_project('project_name')",
332
+ "Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')",
333
+ "Run terminal command": "terminal_interface('command', 'project_name')",
334
+ "Generate code": "generate_code('code_idea')",
335
+ "Summarize text": "summarize_text('text')",
336
+ "Analyze sentiment": "sentiment_analysis('text')",
337
+ "Translate code": "translate_code('code', 'source_language', 'target_language')",
338
+ }
339
+ for command_name, command in preset_commands.items():
340
+ st.write(f"{command_name}: `{command}`")
341
+
342
+ elif app_mode == "Workspace Chat App":
343
+ # Workspace Chat App
344
+ st.header("Workspace Chat App")
345
+
346
+ # Project Workspace Creation
347
+ st.subheader("Create a New Project")
348
+ project_name = st.text_input("Enter project name:")
349
+ if st.button("Create Project"):
350
+ workspace_status = workspace_interface(project_name)
351
+ st.success(workspace_status)
352
+
353
+ # Add Code to Workspace
354
+ st.subheader("Add Code to Workspace")
355
+ code_to_add = st.text_area("Enter code to add to workspace:")
356
+ file_name = st.text_input("Enter file name (e.g. 'app.py'):")
357
+ if st.button("Add Code"):
358
+ add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
359
+ st.success(add_code_status)
360
+
361
+ # Terminal Interface with Project Context
362
+ st.subheader("Terminal (Workspace Context)")
363
+ terminal_input = st.text_input("Enter a command within the workspace:")
364
+ if st.button("Run Command"):
365
+ terminal_output = terminal_interface(terminal_input, project_name)
366
+ st.code(terminal_output, language="bash")
367
+
368
+ # Chat Interface for Guidance
369
+ st.subheader("Chat with CodeCraft for Guidance")
370
+ chat_input = st.text_area("Enter your message for guidance:")
371
+ if st.button("Get Guidance"):
372
+ chat_response = chat_interface(chat_input)
373
+ st.session_state.chat_history.append((chat_input, chat_response))
374
+ st.write(f"CodeCraft: {chat_response}")
375
+
376
+ # Display Chat History
377
+ st.subheader("Chat History")
378
+ for user_input, response in st.session_state.chat_history:
379
+ st.write(f"User: {user_input}")
380
+ st.write(f"CodeCraft: {response}")
381
+
382
+ # Display Terminal History
383
+ st.subheader("Terminal History")
384
+ for command, output in st.session_state.terminal_history:
385
+ st.write(f"Command: {command}")
386
+ st.code(output, language="bash")
387
+
388
+ # Display Projects and Files
389
+ st.subheader("Workspace Projects")
390
+ for project, details in st.session_state.workspace_projects.items():
391
+ st.write(f"Project: {project}")
392
+ for file in details['files']:
393
+ st.write(f" - {file}")
394
+
395
+ # Chat with AI Agents
396
+ st.subheader("Chat with AI Agents")
397
+ selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
398
+ agent_chat_input = st.text_area("Enter your message for the agent:")
399
+ if st.button("Send to Agent"):
400
+ agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
401
+ st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
402
+ st.write(f"{selected_agent}: {agent_chat_response}")
403
+
404
+ # Automate Build Process
405
+ st.subheader("Automate Build Process")
406
+ if st.button("Automate"):
407
+ agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
408
+ summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
409
+ st.write("Autonomous Build Summary:")
410
+ st.write(summary)
411
+ st.write("Next Step:")
412
+ st.write(next_step)
413
+
414
+ # Display current state for debugging
415
+ st.sidebar.subheader("Current State")
416
+ st.sidebar.json(st.session_state.current_state)
417