acecalisto3 commited on
Commit
f3c3b2e
·
verified ·
1 Parent(s): 9ca8bda

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +337 -319
app.py CHANGED
@@ -1,330 +1,348 @@
1
  import os
2
  import subprocess
3
- import random
4
- from huggingface_hub import InferenceClient
5
- import gradio as gr
6
- from safe_search import safe_search
7
- from i_search import google
8
- from i_search import i_search as i_s
9
- from datetime import datetime
10
- import logging
11
- import json
12
-
13
- now = datetime.now()
14
- date_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
15
-
16
- client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
17
-
18
- # --- Set up logging ---
19
- logging.basicConfig(
20
- filename="app.log", # Name of the log file
21
- level=logging.INFO, # Set the logging level (INFO, DEBUG, etc.)
22
- format="%(asctime)s - %(levelname)s - %(message)s",
23
- )
24
-
25
- agents = [
26
- "WEB_DEV",
27
- "AI_SYSTEM_PROMPT",
28
- "PYTHON_CODE_DEV"
29
- ]
30
-
31
- VERBOSE = True
32
- MAX_HISTORY = 5
33
-
34
- PREFIX = """
35
- {date_time_str}
36
- Purpose: {purpose}
37
- Safe Search: {safe_search}
38
- """
39
-
40
- LOG_PROMPT = """
41
- PROMPT: {content}
42
- """
43
-
44
- LOG_RESPONSE = """
45
- RESPONSE: {resp}
46
- """
47
-
48
- COMPRESS_HISTORY_PROMPT = """
49
- You are a helpful AI assistant. Your task is to compress the following history into a summary that is no longer than 512 tokens.
50
- History:
51
- {history}
52
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- ACTION_PROMPT = """
55
- You are a helpful AI assistant. You are working on the task: {task}
56
- Your current history is:
57
- {history}
58
- What is your next thought?
59
- thought:
60
- What is your next action?
61
- action:
62
- """
63
 
64
- TASK_PROMPT = """
65
- You are a helpful AI assistant. Your current history is:
66
- {history}
67
- What is the next task?
68
- task:
69
- """
70
 
71
- UNDERSTAND_TEST_RESULTS_PROMPT = """
72
- You are a helpful AI assistant. The test results are:
73
- {test_results}
74
- What do you want to know about the test results?
75
- thought:
76
- """
 
77
 
78
- def format_prompt(message, history, max_history_turns=2):
79
- prompt = " "
80
- # Keep only the last 'max_history_turns' turns
81
- for user_prompt, bot_response in history[-max_history_turns:]:
82
- prompt += f"[INST] {user_prompt} [/INST] {bot_response} "
83
- prompt += f"[INST] {message} [/INST] "
84
- return prompt
85
-
86
- def run_gpt(
87
- prompt_template,
88
- stop_tokens,
89
- max_tokens,
90
- purpose,
91
- **prompt_kwargs,
92
- ):
93
- seed = random.randint(1, 1111111111111111)
94
- logging.info(f"Seed: {seed}") # Log the seed
95
-
96
- content = PREFIX.format(
97
- date_time_str=date_time_str,
98
- purpose=purpose,
99
- safe_search=safe_search,
100
- ) + prompt_template.format(**prompt_kwargs)
101
- if VERBOSE:
102
- logging.info(LOG_PROMPT.format(content)) # Log the prompt
103
-
104
- resp = client.text_generation(content, max_new_tokens=max_tokens, stop_sequences=stop_tokens, temperature=0.7, top_p=0.8, repetition_penalty=1.5)
105
- if VERBOSE:
106
- logging.info(LOG_RESPONSE.format(resp)) # Log the response
107
- return resp
108
-
109
- def generate(
110
- prompt,
111
- history,
112
- agent_name=agents[0],
113
- sys_prompt="",
114
- temperature=0.7,
115
- max_new_tokens=2048,
116
- top_p=0.8,
117
- repetition_penalty=1.5,
118
- ):
119
- content = PREFIX.format(
120
- date_time_str=date_time_str,
121
- purpose=purpose,
122
- safe_search=safe_search,
123
- ) + prompt
124
- if VERBOSE:
125
- logging.info(LOG_PROMPT.format(content)) # Log the prompt
126
-
127
- stream = client.text_generation(content, stream=True, details=True, return_full_text=False, temperature=temperature, top_p=top_p, repetition_penalty=repetition_penalty, max_new_tokens=max_new_tokens)
128
- resp = ""
129
- for response in stream:
130
- resp += response.token.text
131
-
132
- if VERBOSE:
133
- logging.info(LOG_RESPONSE.format(resp)) # Log the response
134
- return resp
135
-
136
- def compress_history(purpose, task, history, directory):
137
- resp = run_gpt(
138
- COMPRESS_HISTORY_PROMPT,
139
- stop_tokens=["observation:", "task:", "action:", "thought:"],
140
- max_tokens=512,
141
- purpose=purpose,
142
- task=task,
143
- history=history,
144
  )
145
- history = "observation: {}\n".format(resp)
146
- return history
 
 
 
 
 
 
 
 
 
 
 
147
 
148
- def call_search(purpose, task, history, directory, action_input):
149
- logging.info(f"CALLING SEARCH: {action_input}")
150
  try:
151
- if "http" in action_input:
152
- action_input = action_input.strip("<>").strip()
153
- response = i_s(action_input)
154
- logging.info(f"Search Result: {response}")
155
- history += "observation: search result is: {}\n".format(response)
156
- else:
157
- history += "observation: I need to provide a valid URL to 'action: SEARCH action_input=https://URL'\n"
158
- except Exception as e:
159
- history += "observation: {}\n".format(e)
160
- return "MAIN", None, history, task
161
-
162
- def call_main(purpose, task, history, directory, action_input):
163
- logging.info(f"CALLING MAIN: {action_input}")
164
- resp = run_gpt(
165
- ACTION_PROMPT,
166
- stop_tokens=["observation:", "task:", "action:", "thought:"],
167
- max_tokens=32000,
168
- purpose=purpose,
169
- task=task,
170
- history=history,
171
- )
172
- lines = resp.strip().split("\n")
173
- for line in lines:
174
- if line == "":
175
- continue
176
- if line.startswith("thought: "):
177
- history += "{}\n".format(line)
178
- logging.info(f"Thought: {line}")
179
- elif line.startswith("action: "):
180
- action_name, action_input = parse_action(line)
181
- logging.info(f"Action: {action_name} - {action_input}")
182
- history += "{}\n".format(line)
183
- if "COMPLETE" in action_name or "COMPLETE" in action_input:
184
- task = "END"
185
- return action_name, action_input, history, task
186
- else:
187
- return action_name, action_input, history, task
188
- else:
189
- history += "{}\n".format(line)
190
- logging.info(f"Other Output: {line}")
191
- return "MAIN", None, history, task
192
-
193
- def call_set_task(purpose, task, history, directory, action_input):
194
- logging.info(f"CALLING SET_TASK: {action_input}")
195
- task = run_gpt(
196
- TASK_PROMPT,
197
- stop_tokens=[],
198
- max_tokens=64,
199
- purpose=purpose,
200
- task=task,
201
- history=history,
202
- ).strip("\n")
203
- history += "observation: task has been updated to: {}\n".format(task)
204
- return "MAIN", None, history, task
205
-
206
- def end_fn(purpose, task, history, directory, action_input):
207
- logging.info(f"CALLING END_FN: {action_input}")
208
- task = "END"
209
- return "COMPLETE", "COMPLETE", history, task
210
-
211
- NAME_TO_FUNC = {
212
- "MAIN": call_main,
213
- "UPDATE-TASK": call_set_task,
214
- "SEARCH": call_search,
215
- "COMPLETE": end_fn,
216
- }
217
-
218
- def run_action(purpose, task, history, directory, action_name, action_input):
219
- logging.info(f"RUNNING ACTION: {action_name} - {action_input}")
220
- try:
221
- if "RESPONSE" in action_name or "COMPLETE" in action_name:
222
- action_name = "COMPLETE"
223
- task = "END"
224
- return action_name, "COMPLETE", history, task
225
-
226
- # compress the history when it is long
227
- if len(history.split("\n")) > MAX_HISTORY:
228
- logging.info("COMPRESSING HISTORY")
229
- history = compress_history(purpose, task, history, directory)
230
- if action_name not in NAME_TO_FUNC:
231
- action_name = "MAIN"
232
- if action_name == "" or action_name is None:
233
- action_name = "MAIN"
234
- assert action_name in NAME_TO_FUNC
235
-
236
- logging.info(f"RUN: {action_name} - {action_input}")
237
- return NAME_TO_FUNC[action_name](purpose, task, history, directory, action_input)
238
- except Exception as e:
239
- history += "observation: the previous command did not produce any useful output, I need to check the commands syntax, or use a different command\n"
240
- logging.error(f"Error in run_action: {e}")
241
- return "MAIN", None, history, task
242
-
243
- def run(purpose, history):
244
- task = None
245
- directory = "./"
246
- if history:
247
- history = str(history).strip("[]")
248
- if not history:
249
- history = ""
250
-
251
- action_name = "UPDATE-TASK" if task is None else "MAIN"
252
- action_input = None
253
- while True:
254
- logging.info(f"---")
255
- logging.info(f"Purpose: {purpose}")
256
- logging.info(f"Task: {task}")
257
- logging.info(f"---")
258
- logging.info(f"History: {history}")
259
- logging.info(f"---")
260
-
261
- action_name, action_input, history, task = run_action(
262
- purpose,
263
- task,
264
- history,
265
- directory,
266
- action_name,
267
- action_input,
268
- )
269
- yield (history)
270
- if task == "END":
271
- return (history)
272
-
273
- def parse_action(line):
274
- """Parse the action line to get the action name and input."""
275
- parts = line.split(":", 1)
276
- if len(parts) == 2:
277
- action_name = parts[0].replace("action", "").strip()
278
- action_input = parts[1].strip()
279
  else:
280
- action_name = parts[0].replace("action", "").strip()
281
- action_input = ""
282
- return action_name, action_input
283
-
284
- def main():
285
- with gr.Blocks() as demo:
286
- gr.Markdown("## FragMixt")
287
- gr.Markdown("### Agents w/ Agents")
288
-
289
- # Chat Interface
290
- chatbot = gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True, likeable=True, layout="panel")
291
-
292
- # Input Components
293
- message = gr.Textbox(label="Enter your message", placeholder="Ask me anything!")
294
- purpose = gr.Textbox(label="Purpose", placeholder="What is the purpose of this interaction?")
295
- agent_name = gr.Dropdown(label="Agents", choices=[s for s in agents], value=agents[0], interactive=True)
296
- sys_prompt = gr.Textbox(label="System Prompt", max_lines=1, interactive=True)
297
- temperature = gr.Slider(label="Temperature", value=0.9, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Higher values produce more diverse outputs")
298
- max_new_tokens = gr.Slider(label="Max new tokens", value=1048*10, minimum=0, maximum=1048*10, step=64, interactive=True, info="The maximum numbers of new tokens")
299
- top_p = gr.Slider(label="Top-p (nucleus sampling)", value=0.90, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Higher values sample more low-probability tokens")
300
- repetition_penalty = gr.Slider(label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Penalize repeated tokens")
301
-
302
- # Button to submit the message
303
- submit_button = gr.Button(value="Send")
304
-
305
- # Project Explorer Tab
306
- with gr.Tab("Project Explorer"):
307
- project_path = gr.Textbox(label="Project Path", placeholder="/home/user/app/current_project")
308
- explore_button = gr.Button(value="Explore")
309
- project_output = gr.Textbox(label="File Tree", lines=20)
310
-
311
- # Chat App Logic Tab
312
- with gr.Tab("Chat App"):
313
- history = gr.State([])
314
- examples = [
315
- ["What is the purpose of this AI agent?", "I am designed to assist with no-code development tasks."],
316
- ["Can you help me generate a Python function to calculate the factorial of a number?", "Sure! Here is a Python function to calculate the factorial of a number:"],
317
- ]
318
-
319
- def chat(purpose, message, agent_name, sys_prompt, temperature, max_new_tokens, top_p, repetition_penalty, history):
320
- prompt = format_prompt(message, history)
321
- response = generate(prompt, history, agent_name, sys_prompt, temperature, max_new_tokens, top_p, repetition_penalty)
322
- history.append((message, response))
323
- return history, history
324
-
325
- submit_button.click(chat, inputs=[purpose, message, agent_name, sys_prompt, temperature, max_new_tokens, top_p, repetition_penalty, history], outputs=[chatbot, history])
326
-
327
- demo.launch()
328
-
329
- if __name__ == "__main__":
330
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import subprocess
3
+ import streamlit as st
4
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, AutoConfig, AutoModel
5
+
6
+ HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
7
+ PROJECT_ROOT = "projects"
8
+ AGENT_DIRECTORY = "agents"
9
+
10
+ # Global state to manage communication between Tool Box and Workspace Chat App
11
+ if 'chat_history' not in st.session_state:
12
+ st.session_state.chat_history = []
13
+ if 'terminal_history' not in st.session_state:
14
+ st.session_state.terminal_history = []
15
+ if 'workspace_projects' not in st.session_state:
16
+ st.session_state.workspace_projects = {}
17
+ if 'available_agents' not in st.session_state:
18
+ st.session_state.available_agents = []
19
+ if 'current_state' not in st.session_state:
20
+ st.session_state.current_state = {
21
+ 'toolbox': {},
22
+ 'workspace_chat': {}
23
+ }
24
+
25
+ class AIAgent:
26
+ def __init__(self, name, description, skills):
27
+ self.name = name
28
+ self.description = description
29
+ self.skills = skills
30
+
31
+ def create_agent_prompt(self):
32
+ skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
33
+ agent_prompt = f"""
34
+ As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
35
+ {skills_str}
36
+ 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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  """
38
+ return agent_prompt
39
+
40
+ def autonomous_build(self, chat_history, workspace_projects):
41
+ """
42
+ Autonomous build logic that continues based on the state of chat history and workspace projects.
43
+ """
44
+ summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
45
+ summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
46
+
47
+ # Analyze chat history and workspace projects to suggest actions
48
+ # Example:
49
+ # - Check if the user has requested to create a new file
50
+ # - Check if the user has requested to install a package
51
+ # - Check if the user has requested to run a command
52
+ # - Check if the user has requested to generate code
53
+ # - Check if the user has requested to translate code
54
+ # - Check if the user has requested to summarize text
55
+ # - Check if the user has requested to analyze sentiment
56
+
57
+ # Generate a response based on the analysis
58
+ next_step = "Based on the current state, the next logical step is to implement the main application logic."
59
+
60
+ return summary, next_step
61
+
62
+ def load_hf_token():
63
+ return 'YOUR_HF_TOKEN'
64
+
65
+ def save_agent_to_file(agent):
66
+ """Saves the agent's prompt to a file."""
67
+ if not os.path.exists(AGENT_DIRECTORY):
68
+ os.makedirs(AGENT_DIRECTORY)
69
+ file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
70
+ with open(file_path, "w") as file:
71
+ file.write(agent.create_agent_prompt())
72
+ st.session_state.available_agents.append(agent.name)
73
+
74
+ def load_agent_prompt(agent_name):
75
+ """Loads an agent prompt from a file."""
76
+ file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
77
+ if os.path.exists(file_path):
78
+ with open(file_path, "r") as file:
79
+ agent_prompt = file.read()
80
+ return agent_prompt
81
+ else:
82
+ return None
83
 
84
+ def create_agent_from_text(name, text):
85
+ skills = text.split('\n')
86
+ agent = AIAgent(name, "AI agent created from text input.", skills)
87
+ save_agent_to_file(agent)
88
+ return agent.create_agent_prompt()
 
 
 
 
89
 
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
+ model_name = "Bin12345/AutoCoder_S_6.7B"
96
+ try:
97
+ model = AutoModelForCausalLM.from_pretrained(model_name, use_auth_token=load_hf_token())
98
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=load_hf_token())
99
+ generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
100
+ except EnvironmentError as e:
101
+ return f"Error loading model: {e}"
102
 
103
+ combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
104
+
105
+ input_ids = tokenizer.encode(combined_input, return_tensors="pt")
106
+ max_input_length = 900
107
+ if input_ids.shape[1] > max_input_length:
108
+ input_ids = input_ids[:, :max_input_length]
109
+
110
+ outputs = model.generate(
111
+ input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True,
112
+ pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  )
114
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
115
+ return response
116
+
117
+ # Terminal interface
118
+ def terminal_interface(command, project_name=None):
119
+ if project_name:
120
+ project_path = os.path.join(PROJECT_ROOT, project_name)
121
+ if not os.path.exists(project_path):
122
+ return f"Project {project_name} does not exist."
123
+ result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=project_path)
124
+ else:
125
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
126
+ return result.stdout
127
 
128
+ # Code editor interface
129
+ def code_editor_interface(code):
130
  try:
131
+ formatted_code = black.format_str(code, mode=black.FileMode())
132
+ except black.NothingChanged:
133
+ formatted_code = code
134
+
135
+ result = StringIO()
136
+ sys.stdout = result
137
+ sys.stderr = result
138
+
139
+ (pylint_stdout, pylint_stderr) = lint.py_run(code, return_std=True)
140
+ sys.stdout = sys.__stdout__
141
+ sys.stderr = sys.__stderr__
142
+
143
+ lint_message = pylint_stdout.getvalue() + pylint_stderr.getvalue()
144
+
145
+ return formatted_code, lint_message
146
+
147
+ # Text summarization tool
148
+ def summarize_text(text):
149
+ summarizer = pipeline("summarization", model="t5-base", use_auth_token=load_hf_token())
150
+ summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
151
+ return summary[0]['summary_text']
152
+
153
+ # Sentiment analysis tool
154
+ def sentiment_analysis(text):
155
+ analyzer = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment", use_auth_token=load_hf_token())
156
+ result = analyzer(text)
157
+ return result[0]['label']
158
+
159
+ # Text translation tool (code translation)
160
+ def translate_code(code, source_language, target_language):
161
+ # Use a Hugging Face translation model instead of OpenAI
162
+ translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-es", use_auth_token=load_hf_token()) # Example: English to Spanish
163
+ translated_code = translator(code, target_lang=target_language)[0]['translation_text']
164
+ return translated_code
165
+
166
+ def generate_code(code_idea):
167
+ # Use a Hugging Face code generation model instead of OpenAI
168
+ generator = pipeline('text-generation', model='bigcode/starcoder', use_auth_token=load_hf_token())
169
+ generated_code = generator(code_idea, max_length=1000, num_return_sequences=1)[0]['generated_text']
170
+ return generated_code
171
+
172
+ def chat_interface(input_text):
173
+ """Handles general chat interactions with the user."""
174
+ # Use a Hugging Face chatbot model or your own logic
175
+ chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium", use_auth_token=load_hf_token())
176
+ response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
177
+ return response
178
+
179
+ # Workspace interface
180
+ def workspace_interface(project_name):
181
+ project_path = os.path.join(PROJECT_ROOT, project_name)
182
+ if not os.path.exists(project_path):
183
+ os.makedirs(project_path)
184
+ st.session_state.workspace_projects[project_name] = {'files': []}
185
+ return f"Project '{project_name}' created successfully."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  else:
187
+ return f"Project '{project_name}' already exists."
188
+
189
+ # Add code to workspace
190
+ def add_code_to_workspace(project_name, code, file_name):
191
+ project_path = os.path.join(PROJECT_ROOT, project_name)
192
+ if not os.path.exists(project_path):
193
+ return f"Project '{project_name}' does not exist."
194
+
195
+ file_path = os.path.join(project_path, file_name)
196
+ with open(file_path, "w") as file:
197
+ file.write(code)
198
+ st.session_state.workspace_projects[project_name]['files'].append(file_name)
199
+ return f"Code added to '{file_name}' in project '{project_name}'."
200
+
201
+ # Streamlit App
202
+ st.title("AI Agent Creator")
203
+
204
+ # Sidebar navigation
205
+ st.sidebar.title("Navigation")
206
+ app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
207
+
208
+ if app_mode == "AI Agent Creator":
209
+ # AI Agent Creator
210
+ st.header("Create an AI Agent from Text")
211
+
212
+ st.subheader("From Text")
213
+ agent_name = st.text_input("Enter agent name:")
214
+ text_input = st.text_area("Enter skills (one per line):")
215
+ if st.button("Create Agent"):
216
+ agent_prompt = create_agent_from_text(agent_name, text_input)
217
+ st.success(f"Agent '{agent_name}' created and saved successfully.")
218
+ st.session_state.available_agents.append(agent_name)
219
+
220
+ elif app_mode == "Tool Box":
221
+ # Tool Box
222
+ st.header("AI-Powered Tools")
223
+
224
+ # Chat Interface
225
+ st.subheader("Chat with CodeCraft")
226
+ chat_input = st.text_area("Enter your message:")
227
+ if st.button("Send"):
228
+ chat_response = chat_interface(chat_input)
229
+ st.session_state.chat_history.append((chat_input, chat_response))
230
+ st.write(f"CodeCraft: {chat_response}")
231
+
232
+ # Terminal Interface
233
+ st.subheader("Terminal")
234
+ terminal_input = st.text_input("Enter a command:")
235
+ if st.button("Run"):
236
+ terminal_output = terminal_interface(terminal_input)
237
+ st.session_state.terminal_history.append((terminal_input, terminal_output))
238
+ st.code(terminal_output, language="bash")
239
+
240
+ # Code Editor Interface
241
+ st.subheader("Code Editor")
242
+ code_editor = st.text_area("Write your code:", height=300)
243
+ if st.button("Format & Lint"):
244
+ formatted_code, lint_message = code_editor_interface(code_editor)
245
+ st.code(formatted_code, language="python")
246
+ st.info(lint_message)
247
+
248
+ # Text Summarization Tool
249
+ st.subheader("Summarize Text")
250
+ text_to_summarize = st.text_area("Enter text to summarize:")
251
+ if st.button("Summarize"):
252
+ summary = summarize_text(text_to_summarize)
253
+ st.write(f"Summary: {summary}")
254
+
255
+ # Sentiment Analysis Tool
256
+ st.subheader("Sentiment Analysis")
257
+ sentiment_text = st.text_area("Enter text for sentiment analysis:")
258
+ if st.button("Analyze Sentiment"):
259
+ sentiment = sentiment_analysis(sentiment_text)
260
+ st.write(f"Sentiment: {sentiment}")
261
+
262
+ # Text Translation Tool (Code Translation)
263
+ st.subheader("Translate Code")
264
+ code_to_translate = st.text_area("Enter code to translate:")
265
+ source_language = st.text_input("Enter source language (e.g., 'Python'):")
266
+ target_language = st.text_input("Enter target language (e.g., 'JavaScript'):")
267
+ if st.button("Translate Code"):
268
+ translated_code = translate_code(code_to_translate, source_language, target_language)
269
+ st.code(translated_code, language=target_language.lower())
270
+
271
+ # Code Generation
272
+ st.subheader("Code Generation")
273
+ code_idea = st.text_input("Enter your code idea:")
274
+ if st.button("Generate Code"):
275
+ generated_code = generate_code(code_idea)
276
+ st.code(generated_code, language="python")
277
+
278
+ elif app_mode == "Workspace Chat App":
279
+ # Workspace Chat App
280
+ st.header("Workspace Chat App")
281
+
282
+ # Project Workspace Creation
283
+ st.subheader("Create a New Project")
284
+ project_name = st.text_input("Enter project name:")
285
+ if st.button("Create Project"):
286
+ workspace_status = workspace_interface(project_name)
287
+ st.success(workspace_status)
288
+
289
+ # Add Code to Workspace
290
+ st.subheader("Add Code to Workspace")
291
+ code_to_add = st.text_area("Enter code to add to workspace:")
292
+ file_name = st.text_input("Enter file name (e.g., 'app.py'):")
293
+ if st.button("Add Code"):
294
+ add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
295
+ st.success(add_code_status)
296
+
297
+ # Terminal Interface with Project Context
298
+ st.subheader("Terminal (Workspace Context)")
299
+ terminal_input = st.text_input("Enter a command within the workspace:")
300
+ if st.button("Run Command"):
301
+ terminal_output = terminal_interface(terminal_input, project_name)
302
+ st.code(terminal_output, language="bash")
303
+
304
+ # Chat Interface for Guidance
305
+ st.subheader("Chat with CodeCraft for Guidance")
306
+ chat_input = st.text_area("Enter your message for guidance:")
307
+ if st.button("Get Guidance"):
308
+ chat_response = chat_interface(chat_input)
309
+ st.session_state.chat_history.append((chat_input, chat_response))
310
+ st.write(f"CodeCraft: {chat_response}")
311
+
312
+ # Display Chat History
313
+ st.subheader("Chat History")
314
+ for user_input, response in st.session_state.chat_history:
315
+ st.write(f"User: {user_input}")
316
+ st.write(f"CodeCraft: {response}")
317
+
318
+ # Display Terminal History
319
+ st.subheader("Terminal History")
320
+ for command, output in st.session_state.terminal_history:
321
+ st.write(f"Command: {command}")
322
+ st.code(output, language="bash")
323
+
324
+ # Display Projects and Files
325
+ st.subheader("Workspace Projects")
326
+ for project, details in st.session_state.workspace_projects.items():
327
+ st.write(f"Project: {project}")
328
+ for file in details['files']:
329
+ st.write(f" - {file}")
330
+
331
+ # Chat with AI Agents
332
+ st.subheader("Chat with AI Agents")
333
+ selected_agent = st.selectbox("Select an AI agent", st.session_state.available_agents)
334
+ agent_chat_input = st.text_area("Enter your message for the agent:")
335
+ if st.button("Send to Agent"):
336
+ agent_chat_response = chat_interface_with_agent(agent_chat_input, selected_agent)
337
+ st.session_state.chat_history.append((agent_chat_input, agent_chat_response))
338
+ st.write(f"{selected_agent}: {agent_chat_response}")
339
+
340
+ # Automate Build Process
341
+ st.subheader("Automate Build Process")
342
+ if st.button("Automate"):
343
+ agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
344
+ summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects)
345
+ st.write("Autonomous Build Summary:")
346
+ st.write(summary)
347
+ st.write("Next Step:")
348
+ st.write(next_step)