acecalisto3 commited on
Commit
714ba23
1 Parent(s): 4ebd6c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +366 -136
app.py CHANGED
@@ -1,181 +1,411 @@
1
  import os
2
-
3
- import streamlit as st
4
  import subprocess
5
- from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, AutoModel, RagRetriever, AutoModelForSeq2SeqLM
 
6
  import black
7
  from pylint import lint
8
- import sys
9
- import torch
10
- from huggingface_hub import hf_hub_url, cached_download, HfApi
11
- import base64
12
-
13
- # Set your Hugging Face API key here
14
- # hf_token = "YOUR_HUGGING_FACE_API_KEY" # Replace with your actual token
15
- # Get Hugging Face token from secrets.toml - this line should already be in the main code
16
- hf_token = st.secrets["huggingface"]["hf_token"]
17
 
18
  HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
19
  PROJECT_ROOT = "projects"
20
- return refined_response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  class AIAgent:
23
- def __init__(self, name, description, skills, hf_api=None):
24
  self.name = name
25
  self.description = description
26
  self.skills = skills
27
- self._hf_api = hf_api
28
- self._hf_token = hf_token # Store the token here
29
 
30
- @property
31
- def hf_api(self):
32
- if not self._hf_api and self.has_valid_hf_token():
33
- self._hf_api = HfApi(token=self._hf_token)
34
- return self._hf_api
35
 
36
- def has_valid_hf_token(self):
37
- return bool(self._hf_token)
38
-
39
- async def autonomous_build(self, chat_history, workspace_projects, project_name, selected_model, hf_token):
40
- self._hf_token = hf_token
41
- # Continuation of previous methods
42
 
 
 
 
 
43
  summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
44
  summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
45
 
46
- st.error(f"Build Error: {e}")
47
 
48
  return summary, next_step
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- def deploy_built_space_to_hf(self):
51
- if not self._hf_api or not self._hf_token:
52
- raise ValueError("Cannot deploy the Space since no valid Hugoging Face API connection was established.")
 
 
53
 
54
- # Assuming you have a function to get the files for your Space
55
- repository_name = f"my-awesome-space_{datetime.now().timestamp()}"
56
- files = get_built_space_files() # Placeholder - you'll need to define this function
 
 
 
57
 
58
- # Create the Space
59
- create_space(self.hf_api, repository_name, "Description", True, files)
 
 
 
 
 
 
 
 
 
 
60
 
61
- st.markdown("## Congratulations! Successfully deployed Space 🚀 ##")
62
- st.markdown(f"[Check out your new Space here](https://huggingface.co/spaces/{repository_name})")
 
 
 
 
 
 
 
 
 
 
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- # Add any missing functions from your original code (e.g., get_built_space_files)
66
- def get_built_space_files():
67
- # Replace with your logic to gather the files you want to deploy
68
- return {
69
- "app.py": "# Your Streamlit app code here",
70
- "requirements.txt": "streamlit\ntransformers"
71
- # Add other files as needed
72
- }
73
 
74
- def save_agent_to_file(agent):
75
- """Saves the agent's prompt to a file."""
76
- st.session_state.workspace_projects[project_name]['files'].append(file_name)
77
- return f"Code added to '{file_name}' in project '{project_name}'."
78
-
79
- def create_space(api, name, description, public, files, entrypoint="launch.py"):
80
- url = f"{hf_hub_url()}spaces/{name}/prepare-repo"
81
- headers = {"Authorization": f"Bearer {api.access_token}"}
82
- payload = {
83
- "public": public,
84
- "gitignore_template": "web",
85
- "default_branch": "main",
86
- "archived": False,
87
- "files": []
 
 
 
 
 
 
 
 
 
 
 
88
  }
89
- for filename, contents in files.items():
90
- data = {
91
- "content": contents,
92
- "path": filename,
93
- "encoding": "utf-8",
94
- "mode": "overwrite" if "#\{random.randint(0, 1)\}" not in contents else "merge",
95
- }
96
- payload["files"].append(data)
97
- response = requests.post(url, json=payload, headers=headers)
98
- response.raise_for_status()
99
- location = response.headers.get("Location")
100
- # wait_for_processing(location, api) # You might need to implement this if it's not already defined
101
-
102
- return Repository(name=name, api=api)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  # Streamlit App
105
  st.title("AI Agent Creator")
106
 
107
- elif app_mode == "Workspace Chat App":
108
- # Workspace Chat App
109
- st.header("Workspace Chat App")
110
- def get_built_space_files():
111
- """
112
- Gathers the necessary files for the Hugging Face Space,
113
- handling different project structures and file types.
114
- """
115
- files = {}
116
-
117
- # Get the current project name (adjust as needed)
118
- project_name = st.session_state.get('project_name', 'my_project')
119
- project_path = os.path.join(PROJECT_ROOT, project_name)
120
 
121
- # Define a list of files/directories to search for
122
- targets = [
123
- "app.py",
124
- "requirements.txt",
125
- "Dockerfile",
126
- "docker-compose.yml", # Example YAML file
127
- "src", # Example subdirectory
128
- "assets" # Another example subdirectory
129
- ]
130
 
131
- # Iterate through the targets
132
- for target in targets:
133
- target_path = os.path.join(project_path, target)
 
 
 
 
134
 
135
- # If the target is a file, add it to the files dictionary
136
- if os.path.isfile(target_path):
137
- add_file_to_dictionary(files, target_path)
138
 
139
- # If the target is a directory, recursively search for files within it
140
- elif os.path.isdir(target_path):
141
- for root, _, filenames in os.walk(target_path):
142
- for filename in filenames:
143
- file_path = os.path.join(root, filename)
144
- add_file_to_dictionary(files, file_path)
 
 
 
 
 
 
145
 
146
- return files
 
 
 
 
 
 
147
 
148
- def add_file_to_dictionary(files, file_path):
149
- """Helper function to add a file to the files dictionary."""
150
- filename = os.path.relpath(file_path, PROJECT_ROOT) # Get relative path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
- # Handle text and binary files
153
- if filename.endswith((".py", ".txt", ".json", ".html", ".css", ".yml", ".yaml")):
154
- with open(file_path, "r") as f:
155
- files[filename] = f.read()
156
- else:
157
- with open(file_path, "rb") as f:
158
- file_content = f.read()
159
- files[filename] = base64.b64encode(file_content).decode("utf-8")
160
  # Project Workspace Creation
161
  st.subheader("Create a New Project")
162
  project_name = st.text_input("Enter project name:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  st.write(summary)
164
  st.write("Next Step:")
165
  st.write(next_step)
166
-
167
- # Using the modified and extended class and functions, update the callback for the 'Automate' button in the Streamlit UI:
168
- if st.button("Automate", args=(hf_token,)):
169
- agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
170
- summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name, selected_model, hf_token)
171
- st.write("Autonomous Build Summary:")
172
- st.write(summary)
173
- st.write("Next Step:")
174
- st.write(next_step)
175
-
176
- # If everything went well, proceed to deploy the Space
177
- if agent._hf_api and agent.has_valid_hf_token():
178
- agent.deploy_built_space_to_hf()
179
- # Use the hf_token to interact with the Hugging Face API
180
- api = HfApi(token=hf_token)
181
- # Function to create a Space on Hugging Face
 
1
  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"
12
+
13
+ # Global state to manage communication between Tool Box and Workspace Chat App
14
+ if 'chat_history' not in st.session_state:
15
+ st.session_state.chat_history = []
16
+ if 'terminal_history' not in st.session_state:
17
+ st.session_state.terminal_history = []
18
+ if 'workspace_projects' not in st.session_state:
19
+ st.session_state.workspace_projects = {}
20
+ if 'available_agents' not in st.session_state:
21
+ st.session_state.available_agents = []
22
+ if 'current_state' not in st.session_state:
23
+ st.session_state.current_state = {
24
+ 'toolbox': {},
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)