Spaces:
Running
Running
acecalisto3
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,63 +1,31 @@
|
|
1 |
import os
|
2 |
-
import sys
|
3 |
-
import subprocess
|
4 |
-
import base64
|
5 |
-
import json
|
6 |
-
from io import StringIO
|
7 |
-
from typing import Dict, List
|
8 |
|
9 |
import streamlit as st
|
10 |
-
|
|
|
|
|
11 |
from pylint import lint
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
#
|
14 |
-
hf_token =
|
15 |
-
|
16 |
-
|
17 |
-
if "chat_history" not in st.session_state:
|
18 |
-
st.session_state.chat_history = []
|
19 |
-
if "terminal_history" not in st.session_state:
|
20 |
-
st.session_state.terminal_history = []
|
21 |
-
if "workspace_projects" not in st.session_state:
|
22 |
-
st.session_state.workspace_projects = {}
|
23 |
-
|
24 |
-
# Load pre-trained RAG retriever
|
25 |
-
rag_retriever = pipeline("retrieval-question-answering", model="facebook/rag-token-base")
|
26 |
-
|
27 |
-
# Load pre-trained chat model
|
28 |
-
chat_model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/DialoGPT-medium")
|
29 |
-
|
30 |
-
# Load tokenizer
|
31 |
-
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
32 |
-
|
33 |
-
def process_input(user_input: str) -> str:
|
34 |
-
# Input pipeline: Tokenize and preprocess user input
|
35 |
-
input_ids = tokenizer(user_input, return_tensors="pt").input_ids
|
36 |
-
attention_mask = tokenizer(user_input, return_tensors="pt").attention_mask
|
37 |
-
|
38 |
-
# RAG model: Generate response
|
39 |
-
with torch.no_grad():
|
40 |
-
output = rag_retriever(input_ids, attention_mask=attention_mask)
|
41 |
-
response = output.generator_outputs[0].sequences[0]
|
42 |
-
|
43 |
-
# Chat model: Refine response
|
44 |
-
chat_input = tokenizer(response, return_tensors="pt")
|
45 |
-
chat_input["input_ids"] = chat_input["input_ids"].unsqueeze(0)
|
46 |
-
chat_input["attention_mask"] = chat_input["attention_mask"].unsqueeze(0)
|
47 |
-
with torch.no_grad():
|
48 |
-
chat_output = chat_model(**chat_input)
|
49 |
-
refined_response = chat_output.sequences[0]
|
50 |
|
51 |
-
|
|
|
52 |
return refined_response
|
53 |
|
54 |
class AIAgent:
|
55 |
-
def __init__(self, name
|
56 |
self.name = name
|
57 |
self.description = description
|
58 |
self.skills = skills
|
59 |
self._hf_api = hf_api
|
60 |
-
self._hf_token = hf_token
|
61 |
|
62 |
@property
|
63 |
def hf_api(self):
|
@@ -68,653 +36,47 @@ class AIAgent:
|
|
68 |
def has_valid_hf_token(self):
|
69 |
return bool(self._hf_token)
|
70 |
|
71 |
-
async def autonomous_build(self, chat_history
|
|
|
72 |
# Continuation of previous methods
|
73 |
-
summary = "Chat History:\n" + "\n".join(chat_history)
|
74 |
-
summary += "\n\nWorkspace Projects:\n" + "\n".join(workspace_projects.items())
|
75 |
|
76 |
-
|
77 |
-
|
78 |
-
# - Check if the user has requested to create a new file
|
79 |
-
# - Check if the user has requested to install a package
|
80 |
-
# - Check if the user has requested to run a command
|
81 |
-
# - Check if the user has requested to generate code
|
82 |
-
# - Check if the user has requested to translate code
|
83 |
-
# - Check if the user has requested to summarize text
|
84 |
-
# - Check if the user has requested to analyze sentiment
|
85 |
|
86 |
-
|
87 |
-
next_step = "Based on the current state, the next logical step is to implement the main application logic."
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
|
|
93 |
|
94 |
-
#
|
95 |
-
|
96 |
-
|
97 |
-
with open(requirements_file, "w") as f:
|
98 |
-
f.write("# Add your project's dependencies here\n")
|
99 |
|
100 |
-
# Create
|
101 |
-
|
102 |
-
if not os.path.exists(app_file):
|
103 |
-
with open(app_file, "w") as f:
|
104 |
-
f.write("# Your project's main application logic goes here\n")
|
105 |
|
106 |
-
|
107 |
-
|
108 |
-
gui_code = generate_code(
|
109 |
-
"Create a simple GUI for this application", selected_model)
|
110 |
-
with open(app_file, "a") as f:
|
111 |
-
f.write(gui_code)
|
112 |
|
113 |
-
# Run the default build process
|
114 |
-
build_command = "pip install -r requirements.txt && python app.py"
|
115 |
-
try:
|
116 |
-
result = subprocess.run(
|
117 |
-
build_command, shell=True, capture_output=True, text=True, cwd=project_path)
|
118 |
-
st.write(f"Build Output:\n{result.stdout}")
|
119 |
-
if result.stderr:
|
120 |
-
st.error(f"Build Errors:\n{result.stderr}")
|
121 |
-
except Exception as e:
|
122 |
-
st.error(f"Build Error: {e}")
|
123 |
|
124 |
-
|
125 |
-
|
126 |
-
def get_built_space_files() -> Dict[str, str]:
|
127 |
# Replace with your logic to gather the files you want to deploy
|
128 |
return {
|
129 |
"app.py": "# Your Streamlit app code here",
|
130 |
-
"requirements.txt": "streamlit\ntransformers"
|
131 |
# Add other files as needed
|
132 |
}
|
133 |
|
134 |
-
def save_agent_to_file(agent: AIAgent):
|
135 |
-
"""Saves the agent's prompt to a file."""
|
136 |
-
if not os.path.exists(AGENT_DIRECTORY):
|
137 |
-
os.makedirs(AGENT_DIRECTORY)
|
138 |
-
file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
|
139 |
-
with open(file_path, "w") as file:
|
140 |
-
file.write(agent.create_agent_prompt())
|
141 |
-
st.session_state.available_agents.append(agent.name)
|
142 |
-
|
143 |
-
def load_agent_prompt(agent_name: str) -> str:
|
144 |
-
"""Loads an agent prompt from a file."""
|
145 |
-
file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
|
146 |
-
if os.path.exists(file_path):
|
147 |
-
with open(file_path, "r") as file:
|
148 |
-
agent_prompt = file.read()
|
149 |
-
return agent_prompt
|
150 |
-
else:
|
151 |
-
return None
|
152 |
-
|
153 |
-
def create_agent_from_text(name: str, text: str) -> str:
|
154 |
-
skills = text.split("\n")
|
155 |
-
agent = AIAgent(name, "AI agent created from text input.", skills)
|
156 |
-
save_agent_to_file(agent)
|
157 |
-
return agent.create_agent_prompt()
|
158 |
-
|
159 |
-
def chat_interface_with_agent(input_text: str, agent_name: str) -> str:
|
160 |
-
agent_prompt = load_agent_prompt(agent_name)
|
161 |
-
if agent_prompt is None:
|
162 |
-
return f"Agent {agent_name} not found."
|
163 |
-
|
164 |
-
model_name = "MaziyarPanahi/Codestral-22B-v0.1-GGUF"import os
|
165 |
-
import subprocess
|
166 |
-
import streamlit as st
|
167 |
-
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
168 |
-
import black
|
169 |
-
from pylint import lint
|
170 |
-
from io import StringIO
|
171 |
-
|
172 |
-
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
|
173 |
-
PROJECT_ROOT = "projects"
|
174 |
-
AGENT_DIRECTORY = "agents"
|
175 |
-
|
176 |
-
# Global state to manage communication between Tool Box and Workspace Chat App
|
177 |
-
if 'chat_history' not in st.session_state:
|
178 |
-
st.session_state.chat_history = []
|
179 |
-
if 'terminal_history' not in st.session_state:
|
180 |
-
st.session_state.terminal_history = []
|
181 |
-
if 'workspace_projects' not in st.session_state:
|
182 |
-
st.session_state.workspace_projects = {}
|
183 |
-
if 'available_agents' not in st.session_state:
|
184 |
-
st.session_state.available_agents = []
|
185 |
-
if 'current_state' not in st.session_state:
|
186 |
-
st.session_state.current_state = {
|
187 |
-
'toolbox': {},
|
188 |
-
'workspace_chat': {}
|
189 |
-
}
|
190 |
-
|
191 |
-
class AIAgent:
|
192 |
-
def __init__(self, name, description, skills):
|
193 |
-
self.name = name
|
194 |
-
self.description = description
|
195 |
-
self.skills = skills
|
196 |
-
|
197 |
-
def create_agent_prompt(self):
|
198 |
-
skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
|
199 |
-
agent_prompt = f"""
|
200 |
-
As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
|
201 |
-
{skills_str}
|
202 |
-
|
203 |
-
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.
|
204 |
-
"""
|
205 |
-
return agent_prompt
|
206 |
-
|
207 |
-
def autonomous_build(self, chat_history, workspace_projects):
|
208 |
-
"""
|
209 |
-
Autonomous build logic that continues based on the state of chat history and workspace projects.
|
210 |
-
"""
|
211 |
-
summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
|
212 |
-
summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
|
213 |
-
|
214 |
-
next_step = "Based on the current state, the next logical step is to implement the main application logic."
|
215 |
-
|
216 |
-
return summary, next_step
|
217 |
-
|
218 |
def save_agent_to_file(agent):
|
219 |
-
"""Saves the agent's prompt to a file
|
220 |
-
if not os.path.exists(AGENT_DIRECTORY):
|
221 |
-
os.makedirs(AGENT_DIRECTORY)
|
222 |
-
file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
|
223 |
-
config_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}Config.txt")
|
224 |
-
with open(file_path, "w") as file:
|
225 |
-
file.write(agent.create_agent_prompt())
|
226 |
-
with open(config_path, "w") as file:
|
227 |
-
file.write(f"Agent Name: {agent.name}\nDescription: {agent.description}")
|
228 |
-
st.session_state.available_agents.append(agent.name)
|
229 |
-
|
230 |
-
commit_and_push_changes(f"Add agent {agent.name}")
|
231 |
-
|
232 |
-
def load_agent_prompt(agent_name):
|
233 |
-
"""Loads an agent prompt from a file."""
|
234 |
-
file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
|
235 |
-
if os.path.exists(file_path):
|
236 |
-
with open(file_path, "r") as file:
|
237 |
-
agent_prompt = file.read()
|
238 |
-
return agent_prompt
|
239 |
-
else:
|
240 |
-
return None
|
241 |
-
|
242 |
-
def create_agent_from_text(name, text):
|
243 |
-
skills = text.split('\n')
|
244 |
-
agent = AIAgent(name, "AI agent created from text input.", skills)
|
245 |
-
save_agent_to_file(agent)
|
246 |
-
return agent.create_agent_prompt()
|
247 |
-
|
248 |
-
# Chat interface using a selected agent
|
249 |
-
def chat_interface_with_agent(input_text, agent_name):
|
250 |
-
agent_prompt = load_agent_prompt(agent_name)
|
251 |
-
if agent_prompt is None:
|
252 |
-
return f"Agent {agent_name} not found."
|
253 |
-
|
254 |
-
# Load the GPT-2 model which is compatible with AutoModelForCausalLM
|
255 |
-
model_name = "gpt2"
|
256 |
-
try:
|
257 |
-
model = AutoModelForCausalLM.from_pretrained(model_name)
|
258 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
259 |
-
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
260 |
-
except EnvironmentError as e:
|
261 |
-
return f"Error loading model: {e}"
|
262 |
-
|
263 |
-
# Combine the agent prompt with user input
|
264 |
-
combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
|
265 |
-
|
266 |
-
# Truncate input text to avoid exceeding the model's maximum length
|
267 |
-
max_input_length = 900
|
268 |
-
input_ids = tokenizer.encode(combined_input, return_tensors="pt")
|
269 |
-
if input_ids.shape[1] > max_input_length:
|
270 |
-
input_ids = input_ids[:, :max_input_length]
|
271 |
-
|
272 |
-
# Generate chatbot response
|
273 |
-
outputs = model.generate(
|
274 |
-
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
|
275 |
-
)
|
276 |
-
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
277 |
-
return response
|
278 |
-
|
279 |
-
def workspace_interface(project_name):
|
280 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
281 |
-
if not os.path.exists(PROJECT_ROOT):
|
282 |
-
os.makedirs(PROJECT_ROOT)
|
283 |
-
if not os.path.exists(project_path):
|
284 |
-
os.makedirs(project_path)
|
285 |
-
st.session_state.workspace_projects[project_name] = {"files": []}
|
286 |
-
st.session_state.current_state['workspace_chat']['project_name'] = project_name
|
287 |
-
commit_and_push_changes(f"Create project {project_name}")
|
288 |
-
return f"Project {project_name} created successfully."
|
289 |
-
else:
|
290 |
-
return f"Project {project_name} already exists."
|
291 |
-
|
292 |
-
def add_code_to_workspace(project_name, code, file_name):
|
293 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
294 |
-
if os.path.exists(project_path):
|
295 |
-
file_path = os.path.join(project_path, file_name)
|
296 |
-
with open(file_path, "w") as file:
|
297 |
-
file.write(code)
|
298 |
-
st.session_state.workspace_projects[project_name]["files"].append(file_name)
|
299 |
-
st.session_state.current_state['workspace_chat']['added_code'] = {"file_name": file_name, "code": code}
|
300 |
-
commit_and_push_changes(f"Add code to {file_name} in project {project_name}")
|
301 |
-
return f"Code added to {file_name} in project {project_name} successfully."
|
302 |
-
else:
|
303 |
-
return f"Project {project_name} does not exist."
|
304 |
-
|
305 |
-
def terminal_interface(command, project_name=None):
|
306 |
-
if project_name:
|
307 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
308 |
-
if not os.path.exists(project_path):
|
309 |
-
return f"Project {project_name} does not exist."
|
310 |
-
result = subprocess.run(command, cwd=project_path, shell=True, capture_output=True, text=True)
|
311 |
-
else:
|
312 |
-
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
313 |
-
if result.returncode == 0:
|
314 |
-
st.session_state.current_state['toolbox']['terminal_output'] = result.stdout
|
315 |
-
return result.stdout
|
316 |
-
else:
|
317 |
-
st.session_state.current_state['toolbox']['terminal_output'] = result.stderr
|
318 |
-
return result.stderr
|
319 |
-
|
320 |
-
def summarize_text(text):
|
321 |
-
summarizer = pipeline("summarization")
|
322 |
-
summary = summarizer(text, max_length=50, min_length=25, do_sample=False)
|
323 |
-
st.session_state.current_state['toolbox']['summary'] = summary[0]['summary_text']
|
324 |
-
return summary[0]['summary_text']
|
325 |
-
|
326 |
-
def sentiment_analysis(text):
|
327 |
-
analyzer = pipeline("sentiment-analysis")
|
328 |
-
sentiment = analyzer(text)
|
329 |
-
st.session_state.current_state['toolbox']['sentiment'] = sentiment[0]
|
330 |
-
return sentiment[0]
|
331 |
-
|
332 |
-
# ... [rest of the translate_code function, but remove the OpenAI API call and replace it with your own logic] ...
|
333 |
-
|
334 |
-
def generate_code(code_idea):
|
335 |
-
# Replace this with a call to a Hugging Face model or your own logic
|
336 |
-
# For example, using a text-generation pipeline:
|
337 |
-
generator = pipeline('text-generation', model='gpt4o')
|
338 |
-
generated_code = generator(code_idea, max_length=10000, num_return_sequences=1)[0]['generated_text']
|
339 |
-
messages=[
|
340 |
-
{"role": "system", "content": "You are an expert software developer."},
|
341 |
-
{"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
|
342 |
-
]
|
343 |
-
st.session_state.current_state['toolbox']['generated_code'] = generated_code
|
344 |
-
|
345 |
-
return generated_code
|
346 |
-
|
347 |
-
def translate_code(code, input_language, output_language):
|
348 |
-
# Define a dictionary to map programming languages to their corresponding file extensions
|
349 |
-
language_extensions = {
|
350 |
-
"Python": "py",
|
351 |
-
"JavaScript": "js",
|
352 |
-
"Java": "java",
|
353 |
-
"C++": "cpp",
|
354 |
-
"C#": "cs",
|
355 |
-
"Ruby": "rb",
|
356 |
-
"Go": "go",
|
357 |
-
"PHP": "php",
|
358 |
-
"Swift": "swift",
|
359 |
-
"TypeScript": "ts",
|
360 |
-
}
|
361 |
-
|
362 |
-
# Add code to handle edge cases such as invalid input and unsupported programming languages
|
363 |
-
if input_language not in language_extensions:
|
364 |
-
raise ValueError(f"Invalid input language: {input_language}")
|
365 |
-
if output_language not in language_extensions:
|
366 |
-
raise ValueError(f"Invalid output language: {output_language}")
|
367 |
-
|
368 |
-
# Use the dictionary to map the input and output languages to their corresponding file extensions
|
369 |
-
input_extension = language_extensions[input_language]
|
370 |
-
output_extension = language_extensions[output_language]
|
371 |
-
|
372 |
-
# Translate the code using the OpenAI API
|
373 |
-
prompt = f"Translate this code from {input_language} to {output_language}:\n\n{code}"
|
374 |
-
response = openai.ChatCompletion.create(
|
375 |
-
model="gpt-4",
|
376 |
-
messages=[
|
377 |
-
{"role": "system", "content": "You are an expert software developer."},
|
378 |
-
{"role": "user", "content": prompt}
|
379 |
-
]
|
380 |
-
)
|
381 |
-
translated_code = response.choices[0].message['content'].strip()
|
382 |
-
|
383 |
-
# Return the translated code
|
384 |
-
translated_code = response.choices[0].message['content'].strip()
|
385 |
-
st.session_state.current_state['toolbox']['translated_code'] = translated_code
|
386 |
-
return translated_code
|
387 |
-
|
388 |
-
def generate_code(code_idea):
|
389 |
-
response = openai.ChatCompletion.create(
|
390 |
-
model="gpt-4",
|
391 |
-
messages=[
|
392 |
-
{"role": "system", "content": "You are an expert software developer."},
|
393 |
-
{"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
|
394 |
-
]
|
395 |
-
)
|
396 |
-
generated_code = response.choices[0].message['content'].strip()
|
397 |
-
st.session_state.current_state['toolbox']['generated_code'] = generated_code
|
398 |
-
return generated_code
|
399 |
-
|
400 |
-
def commit_and_push_changes(commit_message):
|
401 |
-
"""Commits and pushes changes to the Hugging Face repository."""
|
402 |
-
commands = [
|
403 |
-
"git add .",
|
404 |
-
f"git commit -m '{commit_message}'",
|
405 |
-
"git push"
|
406 |
-
]
|
407 |
-
for command in commands:
|
408 |
-
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
409 |
-
if result.returncode != 0:
|
410 |
-
st.error(f"Error executing command '{command}': {result.stderr}")
|
411 |
-
break
|
412 |
-
|
413 |
-
def interact_with_web_interface(agent, api_key, url, payload):
|
414 |
-
"""
|
415 |
-
Interacts with a web interface using the provided API key and payload.
|
416 |
-
|
417 |
-
Args:
|
418 |
-
agent: The AIAgent instance.
|
419 |
-
api_key: The API key for the web interface.
|
420 |
-
url: The URL of the web interface.
|
421 |
-
payload: The payload to send to the web interface.
|
422 |
-
|
423 |
-
Returns:
|
424 |
-
The response from the web interface.
|
425 |
-
"""
|
426 |
-
|
427 |
-
# Use the agent's knowledge to determine the appropriate HTTP method and headers.
|
428 |
-
http_method = agent.get_http_method(url)
|
429 |
-
headers = agent.get_headers(url)
|
430 |
-
|
431 |
-
# Add the API key to the headers.
|
432 |
-
headers["Authorization"] = f"Bearer {api_key}"
|
433 |
-
|
434 |
-
# Send the request to the web interface.
|
435 |
-
response = requests.request(http_method, url, headers=headers, json=payload)
|
436 |
-
|
437 |
-
# Return the response.
|
438 |
-
return response
|
439 |
-
|
440 |
-
def get_http_method(url):
|
441 |
-
"""
|
442 |
-
Determines the appropriate HTTP method for the given URL.
|
443 |
-
|
444 |
-
Args:
|
445 |
-
url: The URL of the web interface.
|
446 |
-
|
447 |
-
Returns:
|
448 |
-
The HTTP method (e.g., "GET", "POST", "PUT", "DELETE").
|
449 |
-
"""
|
450 |
-
|
451 |
-
# Use the agent's knowledge to determine the HTTP method.
|
452 |
-
# For example, the agent might know that the URL is for a REST API endpoint that supports CRUD operations.
|
453 |
-
|
454 |
-
return "GET"
|
455 |
-
|
456 |
-
def get_headers(url):
|
457 |
-
"""
|
458 |
-
Determines the appropriate headers for the given URL.
|
459 |
-
|
460 |
-
Args:
|
461 |
-
url: The URL of the web interface.
|
462 |
-
|
463 |
-
Returns:
|
464 |
-
A dictionary of headers.
|
465 |
-
"""
|
466 |
-
|
467 |
-
# Use the agent's knowledge to determine the headers.
|
468 |
-
# For example, the agent might know that the web interface requires an "Authorization" header with an API key.
|
469 |
-
|
470 |
-
return {"Content-Type": "application/json"}
|
471 |
-
|
472 |
-
# ... (rest of the code)
|
473 |
-
|
474 |
-
if app_mode == "Toolbox":
|
475 |
-
|
476 |
-
# Streamlit App
|
477 |
-
st.title("AI Agent Creator")
|
478 |
-
|
479 |
-
# Sidebar navigation
|
480 |
-
st.sidebar.title("Navigation")
|
481 |
-
app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
|
482 |
-
|
483 |
-
if app_mode == "AI Agent Creator":
|
484 |
-
# AI Agent Creator
|
485 |
-
st.header("Create an AI Agent from Text")
|
486 |
-
|
487 |
-
st.subheader("From Text")
|
488 |
-
agent_name = st.text_input("Enter agent name:")
|
489 |
-
text_input = st.text_area("Enter skills (one per line):")
|
490 |
-
if st.button("Create Agent"):
|
491 |
-
agent_prompt = create_agent_from_text(agent_name, text_input)
|
492 |
-
st.success(f"Agent '{agent_name}' created and saved successfully.")
|
493 |
-
st.session_state.available_agents.append(agent_name)
|
494 |
-
|
495 |
-
elif app_mode == "Tool Box":
|
496 |
-
# Tool Box
|
497 |
-
st.header("AI-Powered Tools")
|
498 |
-
|
499 |
-
# Chat Interface
|
500 |
-
st.subheader("Chat with CodeCraft")
|
501 |
-
chat_input = st.text_area("Enter your message:")
|
502 |
-
if st.button("Send"):
|
503 |
-
if chat_input.startswith("@"):
|
504 |
-
agent_name = chat_input.split(" ")[0][1:] # Extract agent_name from @agent_name
|
505 |
-
chat_input = " ".join(chat_input.split(" ")[1:]) # Remove agent_name from input
|
506 |
-
chat_response = chat_interface_with_agent(chat_input, agent_name)
|
507 |
-
else:
|
508 |
-
chat_response = chat_interface(chat_input)
|
509 |
-
st.session_state.chat_history.append((chat_input, chat_response))
|
510 |
-
st.write(f"CodeCraft: {chat_response}")
|
511 |
-
|
512 |
-
# Terminal Interface
|
513 |
-
st.subheader("Terminal")
|
514 |
-
terminal_input = st.text_input("Enter a command:")
|
515 |
-
if st.button("Run"):
|
516 |
-
terminal_output = terminal_interface(terminal_input)
|
517 |
-
st.session_state.terminal_history.append((terminal_input, terminal_output))
|
518 |
-
st.code(terminal_output, language="bash")
|
519 |
-
|
520 |
-
# Code Editor Interface
|
521 |
-
st.subheader("Code Editor")
|
522 |
-
code_editor = st.text_area("Write your code:", height=300)
|
523 |
-
if st.button("Format & Lint"):
|
524 |
-
formatted_code, lint_message = code_editor_interface(code_editor)
|
525 |
-
st.code(formatted_code, language="python")
|
526 |
-
st.info(lint_message)
|
527 |
-
|
528 |
-
# Text Summarization Tool
|
529 |
-
st.subheader("Summarize Text")
|
530 |
-
text_to_summarize = st.text_area("Enter text to summarize:")
|
531 |
-
if st.button("Summarize"):
|
532 |
-
summary = summarize_text(text_to_summarize)
|
533 |
-
st.write(f"Summary: {summary}")
|
534 |
-
|
535 |
-
# Sentiment Analysis Tool
|
536 |
-
st.subheader("Sentiment Analysis")
|
537 |
-
sentiment_text = st.text_area("Enter text for sentiment analysis:")
|
538 |
-
if st.button("Analyze Sentiment"):
|
539 |
-
sentiment = sentiment_analysis(sentiment_text)
|
540 |
-
st.write(f"Sentiment: {sentiment}")
|
541 |
-
|
542 |
-
# Text Translation Tool (Code Translation)
|
543 |
-
st.subheader("Translate Code")
|
544 |
-
code_to_translate = st.text_area("Enter code to translate:")
|
545 |
-
input_language = st.text_input("Enter input language (e.g. 'Python'):")
|
546 |
-
output_language = st.text_input("Enter output language (e.g. 'JavaScript'):")
|
547 |
-
if st.button("Translate Code"):
|
548 |
-
translated_code = translate_code(code_to_translate, input_language, output_language)
|
549 |
-
st.code(translated_code, language=output_language.lower())
|
550 |
-
|
551 |
-
# Code Generation
|
552 |
-
st.subheader("Code Generation")
|
553 |
-
code_idea = st.text_input("Enter your code idea:")
|
554 |
-
if st.button("Generate Code"):
|
555 |
-
generated_code = generate_code(code_idea)
|
556 |
-
st.code(generated_code, language="python")
|
557 |
-
|
558 |
-
# Display Preset Commands
|
559 |
-
st.subheader("Preset Commands")
|
560 |
-
preset_commands = {
|
561 |
-
"Create a new project": "create_project('project_name')",
|
562 |
-
"Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')",
|
563 |
-
"Run terminal command": "terminal_interface('command', 'project_name')",
|
564 |
-
"Generate code": "generate_code('code_idea')",
|
565 |
-
"Summarize text": "summarize_text('text')",
|
566 |
-
"Analyze sentiment": "sentiment_analysis('text')",
|
567 |
-
"Translate code": "translate_code('code', 'source_language', 'target_language')",
|
568 |
-
}
|
569 |
-
for command_name, command in preset_commands.items():
|
570 |
-
st.write(f"{command_name}: `{command}`")
|
571 |
-
|
572 |
-
elif app_mode == "Workspace Chat App":
|
573 |
-
# Workspace Chat App
|
574 |
-
st.header("Workspace Chat App")
|
575 |
-
|
576 |
-
# Project Workspace Creation
|
577 |
-
st.subheader("Create a New Project")
|
578 |
-
project_name = st.text_input("Enter project name:")
|
579 |
-
if st.button("Create Project"):
|
580 |
-
workspace_status = workspace_interface(project_name)
|
581 |
-
st.success(workspace_status)
|
582 |
-
|
583 |
-
# Add Code to Workspace
|
584 |
-
st.subheader("Add Code to Workspace")
|
585 |
-
code_to_add = st.text_area("Enter code to add to workspace:")
|
586 |
-
file_name = st.text_input("Enter file name (e.g. 'app.py'):")
|
587 |
-
if st.button("Add Code"):
|
588 |
-
add_code_status = add_code_to_workspace(project_name, code_to_add, file_name)
|
589 |
-
st.success(add_code_status)
|
590 |
-
|
591 |
-
# Terminal Interface with Project Context
|
592 |
-
st.subheader("Terminal (Workspace Context)")
|
593 |
-
terminal_input = st.text_input("Enter a command within the workspace:")
|
594 |
-
if st.button("Run Command"):
|
595 |
-
terminal_output = terminal_interface(terminal_input, project_name)
|
596 |
-
st.code(terminal_output, language="bash")
|
597 |
-
|
598 |
-
# Chat Interface for Guidance
|
599 |
-
st.subheader("Chat with CodeCraft for Guidance")
|
600 |
-
chat_input = st.text_area("Enter your message for guidance:")
|
601 |
-
if st.button("Get Guidance"):
|
602 |
-
chat_response = chat_interface(chat_input)
|
603 |
-
st.session_state.chat_history.append((chat_input, chat_response))
|
604 |
-
st.write(f"CodeCraft: {chat_response}")
|
605 |
-
|
606 |
-
# Display Chat History
|
607 |
-
st.subheader("Chat History")
|
608 |
-
for user_input, response in st.session_state.chat_history:
|
609 |
-
st.write(f"User: {user_input}")
|
610 |
-
st.write(f"CodeCraft: {response}")
|
611 |
-
|
612 |
-
# Display Terminal History
|
613 |
-
st.subheader("Terminal History")
|
614 |
-
for command, output in st.session_state.terminal_history:
|
615 |
-
st.write(f"Command: {command}")
|
616 |
-
st.code(output, language="bash")
|
617 |
-
|
618 |
-
# Display Projects and Files
|
619 |
-
st.subheader("Workspace Projects")
|
620 |
-
for project, details in st.session_state.workspace_projects.items():
|
621 |
-
st.write(f"Project: {project}")
|
622 |
-
st.write("Files:")
|
623 |
-
for file in details["files"]:
|
624 |
-
st.write(f"- {file}")
|
625 |
-
try:
|
626 |
-
generator = pipeline("text-generation", model=model_name)
|
627 |
-
generator.tokenizer.pad_token = generator.tokenizer.eos_token
|
628 |
-
generated_response = generator(
|
629 |
-
f"{agent_prompt}\n\nUser: {input_text}\nAgent:", max_length=100, do_sample=True, top_k=50)[0]["generated_text"]
|
630 |
-
return generated_response
|
631 |
-
except Exception as e:
|
632 |
-
return f"Error loading model: {e}"
|
633 |
-
|
634 |
-
def terminal_interface(command: str, project_name: str = None) -> str:
|
635 |
-
if project_name:
|
636 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
637 |
-
if not os.path.exists(project_path):
|
638 |
-
return f"Project {project_name} does not exist."
|
639 |
-
result = subprocess.run(
|
640 |
-
command, shell=True, capture_output=True, text=True, cwd=project_path)
|
641 |
-
else:
|
642 |
-
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
643 |
-
return result.stdout
|
644 |
-
|
645 |
-
def code_editor_interface(code: str) -> str:
|
646 |
-
try:
|
647 |
-
formatted_code = black.format_str(code, mode=black.FileMode())
|
648 |
-
except black.NothingChanged:
|
649 |
-
formatted_code = code
|
650 |
-
|
651 |
-
result = StringIO()
|
652 |
-
sys.stdout = result
|
653 |
-
sys.stderr = result
|
654 |
-
|
655 |
-
(pylint_stdout, pylint_stderr) = lint.py_run(code, return_std=True)
|
656 |
-
sys.stdout = sys.__stdout__
|
657 |
-
sys.stderr = sys.__stderr__
|
658 |
-
|
659 |
-
lint_message = pylint_stdout.getvalue() + pylint_stderr.getvalue()
|
660 |
-
|
661 |
-
return formatted_code, lint_message
|
662 |
-
|
663 |
-
def summarize_text(text: str) -> str:
|
664 |
-
summarizer = pipeline("summarization")
|
665 |
-
summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
|
666 |
-
return summary[0]['summary_text']
|
667 |
-
|
668 |
-
def sentiment_analysis(text: str) -> str:
|
669 |
-
analyzer = pipeline("sentiment-analysis")
|
670 |
-
result = analyzer(text)
|
671 |
-
return result[0]['label']
|
672 |
-
|
673 |
-
def translate_code(code: str, source_language: str, target_language: str) -> str:
|
674 |
-
# Use a Hugging Face translation model instead of OpenAI
|
675 |
-
# Example: English to Spanish
|
676 |
-
translator = pipeline(
|
677 |
-
"translation", model="bartowski/Codestral-22B-v0.1-GGUF")
|
678 |
-
translated_code = translator(code, target_lang=target_language)[0]['translation_text']
|
679 |
-
return translated_code
|
680 |
-
|
681 |
-
def generate_code(code_idea: str, model_name: str) -> str:
|
682 |
-
"""Generates code using the selected model."""
|
683 |
-
try:
|
684 |
-
generator = pipeline('text-generation', model=model_name)
|
685 |
-
generated_code = generator(code_idea, max_length=1000, num_return_sequences=1)[0]['generated_text']
|
686 |
-
return generated_code
|
687 |
-
except Exception as e:
|
688 |
-
return f"Error generating code: {e}"
|
689 |
-
|
690 |
-
def chat_interface(input_text: str) -> str:
|
691 |
-
"""Handles general chat interactions with the user."""
|
692 |
-
# Use a Hugging Face chatbot model or your own logic
|
693 |
-
chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
|
694 |
-
response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
|
695 |
-
return response
|
696 |
-
|
697 |
-
def workspace_interface(project_name: str) -> str:
|
698 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
699 |
-
if not os.path.exists(project_path):
|
700 |
-
os.makedirs(project_path)
|
701 |
-
st.session_state.workspace_projects[project_name] = {'files': []}
|
702 |
-
return f"Project '{project_name}' created successfully."
|
703 |
-
else:
|
704 |
-
return f"Project '{project_name}' already exists."
|
705 |
-
|
706 |
-
def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
|
707 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
708 |
-
if not os.path.exists(project_path):
|
709 |
-
return f"Project '{project_name}' does not exist."
|
710 |
-
|
711 |
-
file_path = os.path.join(project_path, file_name)
|
712 |
-
with open(file_path, "w") as file:
|
713 |
-
file.write(code)
|
714 |
st.session_state.workspace_projects[project_name]['files'].append(file_name)
|
715 |
return f"Code added to '{file_name}' in project '{project_name}'."
|
716 |
|
717 |
-
def
|
718 |
url = f"{hf_hub_url()}spaces/{name}/prepare-repo"
|
719 |
headers = {"Authorization": f"Bearer {api.access_token}"}
|
720 |
payload = {
|
@@ -729,7 +91,7 @@ def create_space_on_hugging_face(api, name, description, public, files, entrypoi
|
|
729 |
"content": contents,
|
730 |
"path": filename,
|
731 |
"encoding": "utf-8",
|
732 |
-
"mode": "overwrite"
|
733 |
}
|
734 |
payload["files"].append(data)
|
735 |
response = requests.post(url, json=payload, headers=headers)
|
@@ -742,193 +104,78 @@ def create_space_on_hugging_face(api, name, description, public, files, entrypoi
|
|
742 |
# Streamlit App
|
743 |
st.title("AI Agent Creator")
|
744 |
|
745 |
-
# Sidebar navigation
|
746 |
-
st.sidebar.title("Navigation")
|
747 |
-
app_mode = st.sidebar.selectbox(
|
748 |
-
"Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
|
749 |
-
|
750 |
-
if app_mode == "AI Agent Creator":
|
751 |
-
# AI Agent Creator
|
752 |
-
st.header("Create an AI Agent from Text")
|
753 |
-
|
754 |
-
st.subheader("From Text")
|
755 |
-
agent_name = st.text_input("Enter agent name:")
|
756 |
-
text_input = st.text_area("Enter skills (one per line):")
|
757 |
-
if st.button("Create Agent"):
|
758 |
-
agent_prompt = create_agent_from_text(agent_name, text_input)
|
759 |
-
st.success(f"Agent '{agent_name}' created and saved successfully.")
|
760 |
-
st.session_state.available_agents.append(agent_name)
|
761 |
-
|
762 |
-
elif app_mode == "Tool Box":
|
763 |
-
# Tool Box
|
764 |
-
st.header("AI-Powered Tools")
|
765 |
-
|
766 |
-
# Chat Interface
|
767 |
-
st.subheader("Chat with CodeCraft")
|
768 |
-
chat_input = st.text_area("Enter your message:")
|
769 |
-
if st.button("Send"):
|
770 |
-
chat_response = chat_interface(chat_input)
|
771 |
-
st.session_state.chat_history.append((chat_input, chat_response))
|
772 |
-
st.write(f"CodeCraft: {chat_response}")
|
773 |
-
|
774 |
-
# Terminal Interface
|
775 |
-
st.subheader("Terminal")
|
776 |
-
terminal_input = st.text_input("Enter a command:")
|
777 |
-
if st.button("Run"):
|
778 |
-
terminal_output = terminal_interface(terminal_input)
|
779 |
-
st.session_state.terminal_history.append(
|
780 |
-
(terminal_input, terminal_output))
|
781 |
-
st.code(terminal_output, language="bash")
|
782 |
-
|
783 |
-
# Code Editor Interface
|
784 |
-
st.subheader("Code Editor")
|
785 |
-
code_editor = st.text_area("Write your code:", height=300)
|
786 |
-
if st.button("Format & Lint"):
|
787 |
-
formatted_code, lint_message = code_editor_interface(code_editor)
|
788 |
-
st.code(formatted_code, language="python")
|
789 |
-
st.info(lint_message)
|
790 |
-
|
791 |
-
# Text Summarization Tool
|
792 |
-
st.subheader("Summarize Text")
|
793 |
-
text_to_summarize = st.text_area("Enter text to summarize:")
|
794 |
-
if st.button("Summarize"):
|
795 |
-
summary = summarize_text(text_to_summarize)
|
796 |
-
st.write(f"Summary: {summary}")
|
797 |
-
|
798 |
-
# Sentiment Analysis Tool
|
799 |
-
st.subheader("Sentiment Analysis")
|
800 |
-
sentiment_text = st.text_area("Enter text for sentiment analysis:")
|
801 |
-
if st.button("Analyze Sentiment"):
|
802 |
-
sentiment = sentiment_analysis(sentiment_text)
|
803 |
-
st.write(f"Sentiment: {sentiment}")
|
804 |
-
|
805 |
-
# Text Translation Tool (Code Translation)
|
806 |
-
st.subheader("Translate Code")
|
807 |
-
code_to_translate = st.text_area("Enter code to translate:")
|
808 |
-
source_language = st.text_input("Enter source language (e.g., 'Python'):")
|
809 |
-
target_language = st.text_input(
|
810 |
-
"Enter target language (e.g., 'JavaScript'):")
|
811 |
-
if st.button("Translate Code"):
|
812 |
-
translated_code = translate_code(
|
813 |
-
code_to_translate, source_language, target_language)
|
814 |
-
st.code(translated_code, language=target_language.lower())
|
815 |
-
|
816 |
-
# Code Generation
|
817 |
-
st.subheader("Code Generation")
|
818 |
-
code_idea = st.text_input("Enter your code idea:")
|
819 |
-
if st.button("Generate Code"):
|
820 |
-
generated_code = generate_code(code_idea)
|
821 |
-
st.code(generated_code, language="python")
|
822 |
-
|
823 |
elif app_mode == "Workspace Chat App":
|
824 |
# Workspace Chat App
|
825 |
st.header("Workspace Chat App")
|
|
|
|
|
|
|
|
|
|
|
|
|
826 |
|
827 |
-
#
|
828 |
-
st.
|
829 |
-
|
830 |
-
if st.button("Create Project"):
|
831 |
-
workspace_status = workspace_interface(project_name)
|
832 |
-
st.success(workspace_status)
|
833 |
-
|
834 |
-
# Automatically create requirements.txt and app.py
|
835 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
836 |
-
requirements_file = os.path.join(project_path, "requirements.txt")
|
837 |
-
if not os.path.exists(requirements_file):
|
838 |
-
with open(requirements_file, "w") as f:
|
839 |
-
f.write("# Add your project's dependencies here\n")
|
840 |
-
|
841 |
-
app_file = os.path.join(project_path, "app.py")
|
842 |
-
if not os.path.exists(app_file):
|
843 |
-
with open(app_file, "w") as f:
|
844 |
-
f.write("# Your project's main application logic goes here\n")
|
845 |
-
|
846 |
-
# Add Code to Workspace
|
847 |
-
st.subheader("Add Code to Workspace")
|
848 |
-
code_to_add = st.text_area("Enter code to add to workspace:")
|
849 |
-
file_name = st.text_input("Enter file name (e.g., 'app.py'):")
|
850 |
-
if st.button("Add Code"):
|
851 |
-
add_code_status = add_code_to_workspace(
|
852 |
-
project_name, code_to_add, file_name)
|
853 |
-
st.session_state.terminal_history.append(
|
854 |
-
(f"Add Code: {code_to_add}", add_code_status))
|
855 |
-
st.success(add_code_status)
|
856 |
-
|
857 |
-
# Terminal Interface with Project Context
|
858 |
-
st.subheader("Terminal (Workspace Context)")
|
859 |
-
terminal_input = st.text_input("Enter a command within the workspace:")
|
860 |
-
if st.button("Run Command"):
|
861 |
-
terminal_output = terminal_interface(terminal_input, project_name)
|
862 |
-
st.session_state.terminal_history.append(
|
863 |
-
(terminal_input, terminal_output))
|
864 |
-
st.code(terminal_output, language="bash")
|
865 |
-
|
866 |
-
# Chat Interface for Guidance
|
867 |
-
st.subheader("Chat with CodeCraft for Guidance")
|
868 |
-
chat_input = st.text_area("Enter your message for guidance:")
|
869 |
-
if st.button("Get Guidance"):
|
870 |
-
chat_response = chat_interface(chat_input)
|
871 |
-
st.session_state.chat_history.append((chat_input, chat_response))
|
872 |
-
st.write(f"CodeCraft: {chat_response}")
|
873 |
-
|
874 |
-
# Display Chat History
|
875 |
-
st.subheader("Chat History")
|
876 |
-
for user_input, response in st.session_state.chat_history:
|
877 |
-
st.write(f"User: {user_input}")
|
878 |
-
st.write(f"CodeCraft: {response}")
|
879 |
|
880 |
-
#
|
881 |
-
|
882 |
-
|
883 |
-
|
884 |
-
|
|
|
|
|
|
|
|
|
885 |
|
886 |
-
#
|
887 |
-
|
888 |
-
|
889 |
-
st.write(f"Project: {project}")
|
890 |
-
for file in details['files']:
|
891 |
-
st.write(f" - {file}")
|
892 |
|
893 |
-
|
894 |
-
|
895 |
-
|
896 |
-
"Select an AI agent", st.session_state.available_agents)
|
897 |
-
agent_chat_input = st.text_area("Enter your message for the agent:")
|
898 |
-
if st.button("Send to Agent"):
|
899 |
-
agent_chat_response = chat_interface_with_agent(
|
900 |
-
agent_chat_input, selected_agent)
|
901 |
-
st.session_state.chat_history.append(
|
902 |
-
(agent_chat_input, agent_chat_response))
|
903 |
-
st.write(f"{selected_agent}: {agent_chat_response}")
|
904 |
|
905 |
-
|
906 |
-
|
907 |
-
|
|
|
|
|
|
|
908 |
|
909 |
-
|
910 |
-
selected_model = st.selectbox(
|
911 |
-
"Select a code-generative model", AVAILABLE_CODE_GENERATIVE_MODELS)
|
912 |
|
913 |
-
|
914 |
-
|
915 |
-
|
916 |
|
917 |
-
#
|
918 |
-
|
919 |
-
|
920 |
-
|
921 |
-
|
922 |
-
|
923 |
-
|
924 |
-
|
|
|
|
|
|
|
925 |
st.write(summary)
|
926 |
st.write("Next Step:")
|
927 |
st.write(next_step)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
928 |
|
929 |
# If everything went well, proceed to deploy the Space
|
930 |
if agent._hf_api and agent.has_valid_hf_token():
|
931 |
-
agent.deploy_built_space_to_hf()
|
932 |
# Use the hf_token to interact with the Hugging Face API
|
933 |
-
api = HfApi(token=
|
934 |
-
|
|
|
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):
|
|
|
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 = {
|
|
|
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)
|
|
|
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
|