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