Spaces:
Running
Running
acecalisto3
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,82 +1,36 @@
|
|
1 |
import os
|
2 |
-
import subprocess
|
3 |
-
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, AutoModel, RagRetriever, AutoModelForSeq2SeqLM
|
4 |
-
import black
|
5 |
-
from pylint import lint
|
6 |
-
from io import StringIO
|
7 |
import sys
|
8 |
-
import
|
9 |
-
from huggingface_hub import hf_hub_url, cached_download, HfApi, InferenceClient
|
10 |
import base64
|
11 |
-
import
|
12 |
-
|
13 |
-
|
14 |
-
rag_retriever = pipeline("retrieval-question-answering", model="distilbert-base-nq")
|
15 |
-
|
16 |
-
st.write("Pipeline created successfully")
|
17 |
-
|
18 |
-
# Add the new HTML code below
|
19 |
-
custom_html = '''
|
20 |
-
<div style='position:fixed;bottom:0;left:0;width:100%;'>
|
21 |
-
<iframe width="100%" scrolling="no" title="CodeGPT Widget" frameborder="0" allowtransparency sandbox="" allowfullscreen="" data-widget-id="c265505c-e667-4af2-b492-291da888ee7c" src="https://widget.codegpt.co/chat-widget.js"></iframe>
|
22 |
-
</div>'''
|
23 |
-
|
24 |
-
# Update the markdown function to accept custom HTML code
|
25 |
-
def markdown_with_custom_html(md, html):
|
26 |
-
md_content = md
|
27 |
-
if html:
|
28 |
-
return f"{md_content}\n\n{html}"
|
29 |
-
else:
|
30 |
-
return md_content
|
31 |
-
|
32 |
-
|
33 |
-
markdown_text = "Compare model responses with me!"
|
34 |
-
markdown_with_custom_html(markdown_text, custom_html)
|
35 |
-
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
hf_token = os.environ.get("HUGGINGFACE_TOKEN")("key")
|
41 |
|
42 |
-
|
43 |
-
|
44 |
-
AGENT_DIRECTORY = "agents"
|
45 |
|
46 |
# Global state to manage communication between Tool Box and Workspace Chat App
|
47 |
-
if
|
48 |
st.session_state.chat_history = []
|
49 |
-
if
|
50 |
st.session_state.terminal_history = []
|
51 |
-
if
|
52 |
st.session_state.workspace_projects = {}
|
53 |
-
if 'available_agents' not in st.session_state:
|
54 |
-
st.session_state.available_agents = []
|
55 |
-
if 'current_state' not in st.session_state:
|
56 |
-
st.session_state.current_state = {
|
57 |
-
'toolbox': {},
|
58 |
-
'workspace_chat': {}
|
59 |
-
}
|
60 |
-
|
61 |
-
# List of top downloaded free code-generative models from Hugging Face Hub
|
62 |
-
AVAILABLE_CODE_GENERATIVE_MODELS = [
|
63 |
-
"bigcode/starcoder", # Popular and powerful
|
64 |
-
"Salesforce/codegen-350M-mono", # Smaller, good for quick tasks
|
65 |
-
"microsoft/CodeGPT-small", # Smaller, good for quick tasks
|
66 |
-
"google/flan-t5-xl", # Powerful, good for complex tasks
|
67 |
-
"facebook/bart-large-cnn", # Good for text-to-code tasks
|
68 |
-
]
|
69 |
|
70 |
# Load pre-trained RAG retriever
|
71 |
-
|
72 |
|
73 |
# Load pre-trained chat model
|
74 |
-
chat_model = AutoModelForSeq2SeqLM.from_pretrained("microsoft/DialoGPT-medium")
|
75 |
|
76 |
# Load tokenizer
|
77 |
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")
|
78 |
|
79 |
-
def process_input(user_input):
|
80 |
# Input pipeline: Tokenize and preprocess user input
|
81 |
input_ids = tokenizer(user_input, return_tensors="pt").input_ids
|
82 |
attention_mask = tokenizer(user_input, return_tensors="pt").attention_mask
|
@@ -98,12 +52,12 @@ def process_input(user_input):
|
|
98 |
return refined_response
|
99 |
|
100 |
class AIAgent:
|
101 |
-
def __init__(self, name, description, skills, hf_api=None):
|
102 |
self.name = name
|
103 |
self.description = description
|
104 |
self.skills = skills
|
105 |
self._hf_api = hf_api
|
106 |
-
self._hf_token = hf_token
|
107 |
|
108 |
@property
|
109 |
def hf_api(self):
|
@@ -114,11 +68,10 @@ class AIAgent:
|
|
114 |
def has_valid_hf_token(self):
|
115 |
return bool(self._hf_token)
|
116 |
|
117 |
-
async def autonomous_build(self, chat_history, workspace_projects, project_name, selected_model
|
118 |
-
self._hf_token = hf_token
|
119 |
# Continuation of previous methods
|
120 |
-
summary = "Chat History:\n" + "\n".join(
|
121 |
-
summary += "\n\nWorkspace Projects:\n" + "\n".join(
|
122 |
|
123 |
# Analyze chat history and workspace projects to suggest actions
|
124 |
# Example:
|
@@ -152,14 +105,16 @@ class AIAgent:
|
|
152 |
|
153 |
# Generate GUI code for app.py if requested
|
154 |
if "create a gui" in summary.lower():
|
155 |
-
gui_code = generate_code(
|
|
|
156 |
with open(app_file, "a") as f:
|
157 |
f.write(gui_code)
|
158 |
|
159 |
# Run the default build process
|
160 |
build_command = "pip install -r requirements.txt && python app.py"
|
161 |
try:
|
162 |
-
result = subprocess.run(
|
|
|
163 |
st.write(f"Build Output:\n{result.stdout}")
|
164 |
if result.stderr:
|
165 |
st.error(f"Build Errors:\n{result.stderr}")
|
@@ -167,32 +122,16 @@ class AIAgent:
|
|
167 |
st.error(f"Build Error: {e}")
|
168 |
|
169 |
return summary, next_step
|
170 |
-
|
171 |
-
def deploy_built_space_to_hf(self):
|
172 |
-
if not self._hf_api or not self._hf_token:
|
173 |
-
raise ValueError("Cannot deploy the Space since no valid Hugoging Face API connection was established.")
|
174 |
-
|
175 |
-
# Assuming you have a function to get the files for your Space
|
176 |
-
repository_name = f"my-awesome-space_{datetime.now().timestamp()}"
|
177 |
-
files = get_built_space_files() # Placeholder - you'll need to define this function
|
178 |
-
|
179 |
-
# Create the Space
|
180 |
-
create_space(self.hf_api, repository_name, "Description", True, files)
|
181 |
-
|
182 |
-
st.markdown("## Congratulations! Successfully deployed Space 🚀 ##")
|
183 |
-
st.markdown(f"[Check out your new Space here](https://huggingface.co/spaces/{repository_name})")
|
184 |
-
|
185 |
|
186 |
-
|
187 |
-
def get_built_space_files():
|
188 |
# Replace with your logic to gather the files you want to deploy
|
189 |
return {
|
190 |
"app.py": "# Your Streamlit app code here",
|
191 |
-
"requirements.txt": "streamlit\ntransformers"
|
192 |
# Add other files as needed
|
193 |
}
|
194 |
|
195 |
-
def save_agent_to_file(agent):
|
196 |
"""Saves the agent's prompt to a file."""
|
197 |
if not os.path.exists(AGENT_DIRECTORY):
|
198 |
os.makedirs(AGENT_DIRECTORY)
|
@@ -201,7 +140,7 @@ def save_agent_to_file(agent):
|
|
201 |
file.write(agent.create_agent_prompt())
|
202 |
st.session_state.available_agents.append(agent.name)
|
203 |
|
204 |
-
def load_agent_prompt(agent_name):
|
205 |
"""Loads an agent prompt from a file."""
|
206 |
file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
|
207 |
if os.path.exists(file_path):
|
@@ -211,53 +150,39 @@ def load_agent_prompt(agent_name):
|
|
211 |
else:
|
212 |
return None
|
213 |
|
214 |
-
def create_agent_from_text(name, text):
|
215 |
-
skills = text.split(
|
216 |
agent = AIAgent(name, "AI agent created from text input.", skills)
|
217 |
save_agent_to_file(agent)
|
218 |
return agent.create_agent_prompt()
|
219 |
|
220 |
-
def chat_interface_with_agent(input_text, agent_name):
|
221 |
agent_prompt = load_agent_prompt(agent_name)
|
222 |
if agent_prompt is None:
|
223 |
return f"Agent {agent_name} not found."
|
224 |
|
225 |
-
model_name ="
|
226 |
try:
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
|
|
232 |
return f"Error loading model: {e}"
|
233 |
|
234 |
-
|
235 |
-
|
236 |
-
input_ids = tokenizer.encode(combined_input, return_tensors="pt")
|
237 |
-
max_input_length = 900
|
238 |
-
if input_ids.shape[1] > max_input_length:
|
239 |
-
input_ids = input_ids[:, :max_input_length]
|
240 |
-
|
241 |
-
outputs = model.generate(
|
242 |
-
input_ids, max_new_tokens=1000, num_return_sequences=1, do_sample=True,
|
243 |
-
pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id
|
244 |
-
)
|
245 |
-
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
246 |
-
return response
|
247 |
-
|
248 |
-
# Terminal interface
|
249 |
-
def terminal_interface(command, project_name=None):
|
250 |
if project_name:
|
251 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
252 |
if not os.path.exists(project_path):
|
253 |
return f"Project {project_name} does not exist."
|
254 |
-
result = subprocess.run(
|
|
|
255 |
else:
|
256 |
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
257 |
return result.stdout
|
258 |
|
259 |
-
|
260 |
-
def code_editor_interface(code):
|
261 |
try:
|
262 |
formatted_code = black.format_str(code, mode=black.FileMode())
|
263 |
except black.NothingChanged:
|
@@ -275,26 +200,25 @@ def code_editor_interface(code):
|
|
275 |
|
276 |
return formatted_code, lint_message
|
277 |
|
278 |
-
|
279 |
-
def summarize_text(text):
|
280 |
summarizer = pipeline("summarization")
|
281 |
summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
|
282 |
return summary[0]['summary_text']
|
283 |
|
284 |
-
|
285 |
-
def sentiment_analysis(text):
|
286 |
analyzer = pipeline("sentiment-analysis")
|
287 |
result = analyzer(text)
|
288 |
return result[0]['label']
|
289 |
|
290 |
-
|
291 |
-
def translate_code(code, source_language, target_language):
|
292 |
# Use a Hugging Face translation model instead of OpenAI
|
293 |
-
|
|
|
|
|
294 |
translated_code = translator(code, target_lang=target_language)[0]['translation_text']
|
295 |
return translated_code
|
296 |
|
297 |
-
def generate_code(code_idea, model_name):
|
298 |
"""Generates code using the selected model."""
|
299 |
try:
|
300 |
generator = pipeline('text-generation', model=model_name)
|
@@ -303,15 +227,14 @@ def generate_code(code_idea, model_name):
|
|
303 |
except Exception as e:
|
304 |
return f"Error generating code: {e}"
|
305 |
|
306 |
-
def chat_interface(input_text):
|
307 |
"""Handles general chat interactions with the user."""
|
308 |
# Use a Hugging Face chatbot model or your own logic
|
309 |
chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
|
310 |
response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
|
311 |
return response
|
312 |
|
313 |
-
|
314 |
-
def workspace_interface(project_name):
|
315 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
316 |
if not os.path.exists(project_path):
|
317 |
os.makedirs(project_path)
|
@@ -320,19 +243,18 @@ def workspace_interface(project_name):
|
|
320 |
else:
|
321 |
return f"Project '{project_name}' already exists."
|
322 |
|
323 |
-
|
324 |
-
def add_code_to_workspace(project_name, code, file_name):
|
325 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
326 |
if not os.path.exists(project_path):
|
327 |
return f"Project '{project_name}' does not exist."
|
328 |
-
|
329 |
file_path = os.path.join(project_path, file_name)
|
330 |
with open(file_path, "w") as file:
|
331 |
file.write(code)
|
332 |
st.session_state.workspace_projects[project_name]['files'].append(file_name)
|
333 |
return f"Code added to '{file_name}' in project '{project_name}'."
|
334 |
|
335 |
-
def
|
336 |
url = f"{hf_hub_url()}spaces/{name}/prepare-repo"
|
337 |
headers = {"Authorization": f"Bearer {api.access_token}"}
|
338 |
payload = {
|
@@ -347,7 +269,7 @@ def create_space(api, name, description, public, files, entrypoint="launch.py"):
|
|
347 |
"content": contents,
|
348 |
"path": filename,
|
349 |
"encoding": "utf-8",
|
350 |
-
"mode": "overwrite"
|
351 |
}
|
352 |
payload["files"].append(data)
|
353 |
response = requests.post(url, json=payload, headers=headers)
|
@@ -362,10 +284,8 @@ st.title("AI Agent Creator")
|
|
362 |
|
363 |
# Sidebar navigation
|
364 |
st.sidebar.title("Navigation")
|
365 |
-
app_mode = st.sidebar.selectbox(
|
366 |
-
|
367 |
-
# Get Hugging Face token from secrets.toml
|
368 |
-
hf_token = st.secrets["huggingface"]
|
369 |
|
370 |
if app_mode == "AI Agent Creator":
|
371 |
# AI Agent Creator
|
@@ -396,7 +316,8 @@ elif app_mode == "Tool Box":
|
|
396 |
terminal_input = st.text_input("Enter a command:")
|
397 |
if st.button("Run"):
|
398 |
terminal_output = terminal_interface(terminal_input)
|
399 |
-
st.session_state.terminal_history.append(
|
|
|
400 |
st.code(terminal_output, language="bash")
|
401 |
|
402 |
# Code Editor Interface
|
@@ -425,9 +346,11 @@ elif app_mode == "Tool Box":
|
|
425 |
st.subheader("Translate Code")
|
426 |
code_to_translate = st.text_area("Enter code to translate:")
|
427 |
source_language = st.text_input("Enter source language (e.g., 'Python'):")
|
428 |
-
target_language = st.text_input(
|
|
|
429 |
if st.button("Translate Code"):
|
430 |
-
translated_code = translate_code(
|
|
|
431 |
st.code(translated_code, language=target_language.lower())
|
432 |
|
433 |
# Code Generation
|
@@ -440,56 +363,7 @@ elif app_mode == "Tool Box":
|
|
440 |
elif app_mode == "Workspace Chat App":
|
441 |
# Workspace Chat App
|
442 |
st.header("Workspace Chat App")
|
443 |
-
def get_built_space_files():
|
444 |
-
"""
|
445 |
-
Gathers the necessary files for the Hugging Face Space,
|
446 |
-
handling different project structures and file types.
|
447 |
-
"""
|
448 |
-
files = {}
|
449 |
-
|
450 |
-
# Get the current project name (adjust as needed)
|
451 |
-
project_name = st.session_state.get('project_name', 'my_project')
|
452 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
453 |
|
454 |
-
# Define a list of files/directories to search for
|
455 |
-
targets = [
|
456 |
-
"app.py",
|
457 |
-
"requirements.txt",
|
458 |
-
"Dockerfile",
|
459 |
-
"docker-compose.yml", # Example YAML file
|
460 |
-
"src", # Example subdirectory
|
461 |
-
"assets" # Another example subdirectory
|
462 |
-
]
|
463 |
-
|
464 |
-
# Iterate through the targets
|
465 |
-
for target in targets:
|
466 |
-
target_path = os.path.join(project_path, target)
|
467 |
-
|
468 |
-
# If the target is a file, add it to the files dictionary
|
469 |
-
if os.path.isfile(target_path):
|
470 |
-
add_file_to_dictionary(files, target_path)
|
471 |
-
|
472 |
-
# If the target is a directory, recursively search for files within it
|
473 |
-
elif os.path.isdir(target_path):
|
474 |
-
for root, _, filenames in os.walk(target_path):
|
475 |
-
for filename in filenames:
|
476 |
-
file_path = os.path.join(root, filename)
|
477 |
-
add_file_to_dictionary(files, file_path)
|
478 |
-
|
479 |
-
return files
|
480 |
-
|
481 |
-
def add_file_to_dictionary(files, file_path):
|
482 |
-
"""Helper function to add a file to the files dictionary."""
|
483 |
-
filename = os.path.relpath(file_path, PROJECT_ROOT) # Get relative path
|
484 |
-
|
485 |
-
# Handle text and binary files
|
486 |
-
if filename.endswith((".py", ".txt", ".json", ".html", ".css", ".yml", ".yaml")):
|
487 |
-
with open(file_path, "r") as f:
|
488 |
-
files[filename] = f.read()
|
489 |
-
else:
|
490 |
-
with open(file_path, "rb") as f:
|
491 |
-
file_content = f.read()
|
492 |
-
files[filename] = base64.b64encode(file_content).decode("utf-8")
|
493 |
# Project Workspace Creation
|
494 |
st.subheader("Create a New Project")
|
495 |
project_name = st.text_input("Enter project name:")
|
@@ -514,8 +388,10 @@ def add_file_to_dictionary(files, file_path):
|
|
514 |
code_to_add = st.text_area("Enter code to add to workspace:")
|
515 |
file_name = st.text_input("Enter file name (e.g., 'app.py'):")
|
516 |
if st.button("Add Code"):
|
517 |
-
add_code_status = add_code_to_workspace(
|
518 |
-
|
|
|
|
|
519 |
st.success(add_code_status)
|
520 |
|
521 |
# Terminal Interface with Project Context
|
@@ -523,7 +399,8 @@ def add_file_to_dictionary(files, file_path):
|
|
523 |
terminal_input = st.text_input("Enter a command within the workspace:")
|
524 |
if st.button("Run Command"):
|
525 |
terminal_output = terminal_interface(terminal_input, project_name)
|
526 |
-
st.session_state.terminal_history.append(
|
|
|
527 |
st.code(terminal_output, language="bash")
|
528 |
|
529 |
# Chat Interface for Guidance
|
@@ -555,11 +432,14 @@ def add_file_to_dictionary(files, file_path):
|
|
555 |
|
556 |
# Chat with AI Agents
|
557 |
st.subheader("Chat with AI Agents")
|
558 |
-
selected_agent = st.selectbox(
|
|
|
559 |
agent_chat_input = st.text_area("Enter your message for the agent:")
|
560 |
if st.button("Send to Agent"):
|
561 |
-
agent_chat_response = chat_interface_with_agent(
|
562 |
-
|
|
|
|
|
563 |
st.write(f"{selected_agent}: {agent_chat_response}")
|
564 |
|
565 |
# Code Generation
|
@@ -567,7 +447,8 @@ def add_file_to_dictionary(files, file_path):
|
|
567 |
code_idea = st.text_input("Enter your code idea:")
|
568 |
|
569 |
# Model Selection Menu
|
570 |
-
selected_model = st.selectbox(
|
|
|
571 |
|
572 |
if st.button("Generate Code"):
|
573 |
generated_code = generate_code(code_idea, selected_model)
|
@@ -576,17 +457,10 @@ def add_file_to_dictionary(files, file_path):
|
|
576 |
# Automate Build Process
|
577 |
st.subheader("Automate Build Process")
|
578 |
if st.button("Automate"):
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
st.write("Next Step:")
|
584 |
-
st.write(next_step)
|
585 |
-
|
586 |
-
# Using the modified and extended class and functions, update the callback for the 'Automate' button in the Streamlit UI:
|
587 |
-
if st.button("Automate", args=(hf_token,)):
|
588 |
-
agent = AIAgent(selected_agent, "", []) # Load the agent without skills for now
|
589 |
-
summary, next_step = agent.autonomous_build(st.session_state.chat_history, st.session_state.workspace_projects, project_name, selected_model, hf_token)
|
590 |
st.write("Autonomous Build Summary:")
|
591 |
st.write(summary)
|
592 |
st.write("Next Step:")
|
@@ -594,11 +468,7 @@ def add_file_to_dictionary(files, file_path):
|
|
594 |
|
595 |
# If everything went well, proceed to deploy the Space
|
596 |
if agent._hf_api and agent.has_valid_hf_token():
|
597 |
-
agent.deploy_built_space_to_hf()
|
598 |
# Use the hf_token to interact with the Hugging Face API
|
599 |
-
api = HfApi(token="
|
600 |
-
|
601 |
-
def create_space(api, name, description, public, files, entrypoint="launch.py"):
|
602 |
-
url = f"{hf_hub_url()}spaces/{name}/prepare-repo"
|
603 |
-
headers = {"Authorization": f"Bearer {api.access_token}"}
|
604 |
-
|
|
|
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 |
+
from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer
|
11 |
+
from pylint import lint
|
|
|
12 |
|
13 |
+
# Add your Hugging Face API token here
|
14 |
+
hf_token = st.secrets["hf_token"]
|
|
|
15 |
|
16 |
# Global state to manage communication between Tool Box and Workspace Chat App
|
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
|
|
|
52 |
return refined_response
|
53 |
|
54 |
class AIAgent:
|
55 |
+
def __init__(self, name: str, description: str, skills: List[str], hf_api=None):
|
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 |
def has_valid_hf_token(self):
|
69 |
return bool(self._hf_token)
|
70 |
|
71 |
+
async def autonomous_build(self, chat_history: List[str], workspace_projects: Dict[str, str], project_name: str, selected_model: str):
|
|
|
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 |
# Analyze chat history and workspace projects to suggest actions
|
77 |
# Example:
|
|
|
105 |
|
106 |
# Generate GUI code for app.py if requested
|
107 |
if "create a gui" in summary.lower():
|
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}")
|
|
|
122 |
st.error(f"Build Error: {e}")
|
123 |
|
124 |
return summary, next_step
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
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):
|
|
|
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"
|
165 |
try:
|
166 |
+
generator = pipeline("text-generation", model=model_name)
|
167 |
+
generator.tokenizer.pad_token = generator.tokenizer.eos_token
|
168 |
+
generated_response = generator(
|
169 |
+
f"{agent_prompt}\n\nUser: {input_text}\nAgent:", max_length=100, do_sample=True, top_k=50)[0]["generated_text"]
|
170 |
+
return generated_response
|
171 |
+
except Exception as e:
|
172 |
return f"Error loading model: {e}"
|
173 |
|
174 |
+
def terminal_interface(command: str, project_name: str = None) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
175 |
if project_name:
|
176 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
177 |
if not os.path.exists(project_path):
|
178 |
return f"Project {project_name} does not exist."
|
179 |
+
result = subprocess.run(
|
180 |
+
command, shell=True, capture_output=True, text=True, cwd=project_path)
|
181 |
else:
|
182 |
result = subprocess.run(command, shell=True, capture_output=True, text=True)
|
183 |
return result.stdout
|
184 |
|
185 |
+
def code_editor_interface(code: str) -> str:
|
|
|
186 |
try:
|
187 |
formatted_code = black.format_str(code, mode=black.FileMode())
|
188 |
except black.NothingChanged:
|
|
|
200 |
|
201 |
return formatted_code, lint_message
|
202 |
|
203 |
+
def summarize_text(text: str) -> str:
|
|
|
204 |
summarizer = pipeline("summarization")
|
205 |
summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
|
206 |
return summary[0]['summary_text']
|
207 |
|
208 |
+
def sentiment_analysis(text: str) -> str:
|
|
|
209 |
analyzer = pipeline("sentiment-analysis")
|
210 |
result = analyzer(text)
|
211 |
return result[0]['label']
|
212 |
|
213 |
+
def translate_code(code: str, source_language: str, target_language: str) -> str:
|
|
|
214 |
# Use a Hugging Face translation model instead of OpenAI
|
215 |
+
# Example: English to Spanish
|
216 |
+
translator = pipeline(
|
217 |
+
"translation", model="bartowski/Codestral-22B-v0.1-GGUF")
|
218 |
translated_code = translator(code, target_lang=target_language)[0]['translation_text']
|
219 |
return translated_code
|
220 |
|
221 |
+
def generate_code(code_idea: str, model_name: str) -> str:
|
222 |
"""Generates code using the selected model."""
|
223 |
try:
|
224 |
generator = pipeline('text-generation', model=model_name)
|
|
|
227 |
except Exception as e:
|
228 |
return f"Error generating code: {e}"
|
229 |
|
230 |
+
def chat_interface(input_text: str) -> str:
|
231 |
"""Handles general chat interactions with the user."""
|
232 |
# Use a Hugging Face chatbot model or your own logic
|
233 |
chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
|
234 |
response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
|
235 |
return response
|
236 |
|
237 |
+
def workspace_interface(project_name: str) -> str:
|
|
|
238 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
239 |
if not os.path.exists(project_path):
|
240 |
os.makedirs(project_path)
|
|
|
243 |
else:
|
244 |
return f"Project '{project_name}' already exists."
|
245 |
|
246 |
+
def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
|
|
|
247 |
project_path = os.path.join(PROJECT_ROOT, project_name)
|
248 |
if not os.path.exists(project_path):
|
249 |
return f"Project '{project_name}' does not exist."
|
250 |
+
|
251 |
file_path = os.path.join(project_path, file_name)
|
252 |
with open(file_path, "w") as file:
|
253 |
file.write(code)
|
254 |
st.session_state.workspace_projects[project_name]['files'].append(file_name)
|
255 |
return f"Code added to '{file_name}' in project '{project_name}'."
|
256 |
|
257 |
+
def create_space_on_hugging_face(api, name, description, public, files, entrypoint="launch.py"):
|
258 |
url = f"{hf_hub_url()}spaces/{name}/prepare-repo"
|
259 |
headers = {"Authorization": f"Bearer {api.access_token}"}
|
260 |
payload = {
|
|
|
269 |
"content": contents,
|
270 |
"path": filename,
|
271 |
"encoding": "utf-8",
|
272 |
+
"mode": "overwrite"
|
273 |
}
|
274 |
payload["files"].append(data)
|
275 |
response = requests.post(url, json=payload, headers=headers)
|
|
|
284 |
|
285 |
# Sidebar navigation
|
286 |
st.sidebar.title("Navigation")
|
287 |
+
app_mode = st.sidebar.selectbox(
|
288 |
+
"Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
|
|
|
|
|
289 |
|
290 |
if app_mode == "AI Agent Creator":
|
291 |
# AI Agent Creator
|
|
|
316 |
terminal_input = st.text_input("Enter a command:")
|
317 |
if st.button("Run"):
|
318 |
terminal_output = terminal_interface(terminal_input)
|
319 |
+
st.session_state.terminal_history.append(
|
320 |
+
(terminal_input, terminal_output))
|
321 |
st.code(terminal_output, language="bash")
|
322 |
|
323 |
# Code Editor Interface
|
|
|
346 |
st.subheader("Translate Code")
|
347 |
code_to_translate = st.text_area("Enter code to translate:")
|
348 |
source_language = st.text_input("Enter source language (e.g., 'Python'):")
|
349 |
+
target_language = st.text_input(
|
350 |
+
"Enter target language (e.g., 'JavaScript'):")
|
351 |
if st.button("Translate Code"):
|
352 |
+
translated_code = translate_code(
|
353 |
+
code_to_translate, source_language, target_language)
|
354 |
st.code(translated_code, language=target_language.lower())
|
355 |
|
356 |
# Code Generation
|
|
|
363 |
elif app_mode == "Workspace Chat App":
|
364 |
# Workspace Chat App
|
365 |
st.header("Workspace Chat App")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
366 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
367 |
# Project Workspace Creation
|
368 |
st.subheader("Create a New Project")
|
369 |
project_name = st.text_input("Enter project name:")
|
|
|
388 |
code_to_add = st.text_area("Enter code to add to workspace:")
|
389 |
file_name = st.text_input("Enter file name (e.g., 'app.py'):")
|
390 |
if st.button("Add Code"):
|
391 |
+
add_code_status = add_code_to_workspace(
|
392 |
+
project_name, code_to_add, file_name)
|
393 |
+
st.session_state.terminal_history.append(
|
394 |
+
(f"Add Code: {code_to_add}", add_code_status))
|
395 |
st.success(add_code_status)
|
396 |
|
397 |
# Terminal Interface with Project Context
|
|
|
399 |
terminal_input = st.text_input("Enter a command within the workspace:")
|
400 |
if st.button("Run Command"):
|
401 |
terminal_output = terminal_interface(terminal_input, project_name)
|
402 |
+
st.session_state.terminal_history.append(
|
403 |
+
(terminal_input, terminal_output))
|
404 |
st.code(terminal_output, language="bash")
|
405 |
|
406 |
# Chat Interface for Guidance
|
|
|
432 |
|
433 |
# Chat with AI Agents
|
434 |
st.subheader("Chat with AI Agents")
|
435 |
+
selected_agent = st.selectbox(
|
436 |
+
"Select an AI agent", st.session_state.available_agents)
|
437 |
agent_chat_input = st.text_area("Enter your message for the agent:")
|
438 |
if st.button("Send to Agent"):
|
439 |
+
agent_chat_response = chat_interface_with_agent(
|
440 |
+
agent_chat_input, selected_agent)
|
441 |
+
st.session_state.chat_history.append(
|
442 |
+
(agent_chat_input, agent_chat_response))
|
443 |
st.write(f"{selected_agent}: {agent_chat_response}")
|
444 |
|
445 |
# Code Generation
|
|
|
447 |
code_idea = st.text_input("Enter your code idea:")
|
448 |
|
449 |
# Model Selection Menu
|
450 |
+
selected_model = st.selectbox(
|
451 |
+
"Select a code-generative model", AVAILABLE_CODE_GENERATIVE_MODELS)
|
452 |
|
453 |
if st.button("Generate Code"):
|
454 |
generated_code = generate_code(code_idea, selected_model)
|
|
|
457 |
# Automate Build Process
|
458 |
st.subheader("Automate Build Process")
|
459 |
if st.button("Automate"):
|
460 |
+
# Load the agent without skills for now
|
461 |
+
agent = AIAgent(selected_agent, "", [])
|
462 |
+
summary, next_step = agent.autonomous_build(
|
463 |
+
st.session_state.chat_history, st.session_state.workspace_projects, project_name, selected_model)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
464 |
st.write("Autonomous Build Summary:")
|
465 |
st.write(summary)
|
466 |
st.write("Next Step:")
|
|
|
468 |
|
469 |
# If everything went well, proceed to deploy the Space
|
470 |
if agent._hf_api and agent.has_valid_hf_token():
|
471 |
+
agent.deploy_built_space_to_hf()
|
472 |
# Use the hf_token to interact with the Hugging Face API
|
473 |
+
api = HfApi(token="hf_token") # Function to create a Space on Hugging Face
|
474 |
+
create_space_on_hugging_face(api, agent.name, agent.description, True, get_built_space_files())
|
|
|
|
|
|
|
|