Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -21,10 +21,13 @@ if not hf_token:
|
|
21 |
st.error("Hugging Face API key not found. Please make sure it is set in the secrets.")
|
22 |
|
23 |
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/0shotTest"
|
24 |
-
PROJECT_ROOT =
|
25 |
-
AGENT_DIRECTORY = "agents"
|
26 |
AVAILABLE_CODE_GENERATIVE_MODELS = ["bigcode/starcoder", "Salesforce/codegen-350M-mono", "microsoft/CodeGPT-small"]
|
27 |
|
|
|
|
|
|
|
|
|
28 |
# Global state management
|
29 |
if 'chat_history' not in st.session_state:
|
30 |
st.session_state.chat_history = []
|
@@ -32,8 +35,8 @@ if 'terminal_history' not in st.session_state:
|
|
32 |
st.session_state.terminal_history = []
|
33 |
if 'workspace_projects' not in st.session_state:
|
34 |
st.session_state.workspace_projects = {}
|
35 |
-
if '
|
36 |
-
st.session_state.
|
37 |
|
38 |
# AI Guide Toggle
|
39 |
ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial Assistance", "No Assistance"])
|
@@ -42,27 +45,15 @@ ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial
|
|
42 |
code_generator_tokenizer = AutoTokenizer.from_pretrained("microsoft/CodeGPT-small-py", clean_up_tokenization_spaces=True)
|
43 |
code_generator = pipeline("text-generation", model="microsoft/CodeGPT-small-py", tokenizer=code_generator_tokenizer)
|
44 |
|
45 |
-
class TextGenerationTool:
|
46 |
-
def __init__(self, llm: str):
|
47 |
-
self.llm = llm
|
48 |
-
self.tokenizer = AutoTokenizer.from_pretrained(llm)
|
49 |
-
self.model = AutoModelForCausalLM.from_pretrained(llm)
|
50 |
-
|
51 |
-
def generate_text(self, prompt: str, max_length: int = 50) -> str:
|
52 |
-
inputs = self.tokenizer(prompt, return_tensors="pt")
|
53 |
-
outputs = self.model.generate(**inputs, max_length=max_length)
|
54 |
-
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
55 |
-
|
56 |
class AIAgent:
|
57 |
-
def __init__(self, name: str, description: str, skills: List[str]
|
58 |
self.name = name
|
59 |
self.description = description
|
60 |
self.skills = skills
|
61 |
-
self.text_gen_tool = TextGenerationTool(llm)
|
62 |
-
self._hf_api = HfApi()
|
63 |
|
64 |
def generate_agent_response(self, prompt: str) -> str:
|
65 |
-
|
|
|
66 |
|
67 |
def create_agent_prompt(self) -> str:
|
68 |
skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
|
@@ -73,230 +64,90 @@ I am confident that I can leverage my expertise to assist you in developing and
|
|
73 |
"""
|
74 |
return agent_prompt
|
75 |
|
76 |
-
def
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
)
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
)
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium", tokenizer="microsoft/DialoGPT-medium", clean_up_tokenization_spaces=True)
|
106 |
-
response = chatbot(input_text, max_length=50, num_return_sequences=1)[0]['generated_text']
|
107 |
-
return response
|
108 |
-
|
109 |
-
def run_code(code: str) -> str:
|
110 |
-
try:
|
111 |
-
result = subprocess.run(code, shell=True, capture_output=True, text=True)
|
112 |
-
return result.stdout
|
113 |
-
except Exception as e:
|
114 |
-
return str(e)
|
115 |
-
|
116 |
-
def workspace_interface(project_name: str) -> str:
|
117 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
118 |
-
if not os.path.exists(project_path):
|
119 |
-
os.makedirs(project_path)
|
120 |
-
st.session_state.workspace_projects[project_name] = {'files': []}
|
121 |
-
return f"Project '{project_name}' created successfully."
|
122 |
-
else:
|
123 |
-
return f"Project '{project_name}' already exists."
|
124 |
-
|
125 |
-
def add_code_to_workspace(project_name: str, code: str, file_name: str) -> str:
|
126 |
-
project_path = os.path.join(PROJECT_ROOT, project_name)
|
127 |
-
if not os.path.exists(project_path):
|
128 |
-
return f"Project '{project_name}' does not exist."
|
129 |
-
|
130 |
-
file_path = os.path.join(project_path, file_name)
|
131 |
-
with open(file_path, "w") as file:
|
132 |
-
file.write(code)
|
133 |
-
st.session_state.workspace_projects[project_name]['files'].append(file_name)
|
134 |
-
return f"Code added to '{file_name}' in project '{project_name}'."
|
135 |
-
|
136 |
-
def display_chat_history(chat_history: List[tuple[str, str]]) -> str:
|
137 |
-
return "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
|
138 |
-
|
139 |
-
def display_workspace_projects(workspace_projects: Dict[str, Dict]) -> str:
|
140 |
-
return "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
|
141 |
-
|
142 |
-
def generate_space_content(project_name: str) -> str:
|
143 |
-
return "import streamlit as st\nst.title('My Streamlit App')\nst.write('Hello, world!')"
|
144 |
-
|
145 |
-
def analyze_code(code: str) -> List[str]:
|
146 |
-
hints = []
|
147 |
-
|
148 |
-
if re.search(r'for .* in .*:\n\s+.*\.append\(', code):
|
149 |
-
hints.append("Consider using a list comprehension instead of a loop for appending to a list.")
|
150 |
-
|
151 |
-
if re.search(r'\".*\%s\"|\'.*\%s\'', code) or re.search(r'\".*\%d\"|\'.*\%d\'', code):
|
152 |
-
hints.append("Consider using f-strings for cleaner and more efficient string formatting.")
|
153 |
-
|
154 |
-
if re.search(r'\bglobal\b', code):
|
155 |
-
hints.append("Avoid using global variables. Consider passing parameters or using classes.")
|
156 |
-
|
157 |
-
if re.search(r'open\(.+\)', code) and not re.search(r'with open\(.+\)', code):
|
158 |
-
hints.append("Consider using the `with` statement when opening files to ensure proper resource management.")
|
159 |
-
|
160 |
-
return hints
|
161 |
-
|
162 |
-
def get_code_completion(prompt: str) -> str:
|
163 |
-
completions = code_generator(prompt, max_new_tokens=50, num_return_sequences=1)
|
164 |
-
return completions[0]['generated_text']
|
165 |
-
|
166 |
-
def lint_code(code: str) -> List[str]:
|
167 |
-
pylint_output = StringIO()
|
168 |
-
sys.stdout = pylint_output
|
169 |
-
|
170 |
-
lint.Run(['--from-stdin'], do_exit=False, input=code)
|
171 |
-
|
172 |
-
sys.stdout = sys.__stdout__
|
173 |
-
|
174 |
-
messages = pylint_output.getvalue().splitlines()
|
175 |
-
|
176 |
-
return messages
|
177 |
|
178 |
-
|
179 |
-
|
180 |
-
|
|
|
|
|
|
|
181 |
|
182 |
def main():
|
183 |
-
st.title("
|
184 |
-
|
185 |
-
#
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
st.write(f"**{agent.name}**: {agent.description}")
|
197 |
-
|
198 |
-
# Select an agent
|
199 |
-
selected_agent = st.selectbox("Select an Agent", [agent.name for agent in st.session_state.available_agents])
|
200 |
-
current_agent = next((agent for agent in st.session_state.available_agents if agent.name == selected_agent), None)
|
201 |
-
|
202 |
-
# Display the agent's prompt
|
203 |
-
if current_agent:
|
204 |
-
st.subheader(f"{current_agent.name} Prompt")
|
205 |
-
st.write(current_agent.create_agent_prompt())
|
206 |
|
207 |
-
#
|
208 |
-
st.
|
209 |
-
|
210 |
|
211 |
-
|
212 |
-
|
213 |
-
st.subheader("Chat with your Agent")
|
214 |
user_input = st.text_input("Enter your message:")
|
215 |
-
|
216 |
-
|
217 |
-
st.session_state.chat_history.append((user_input,
|
218 |
-
user_input = "" # Clear the input field
|
219 |
|
220 |
# Display chat history
|
221 |
-
st.
|
222 |
-
|
223 |
-
|
224 |
-
if ai_guide_level != "No Assistance":
|
225 |
-
st.subheader("AI Guide")
|
226 |
-
guide_chat_history = []
|
227 |
-
if ai_guide_level == "Full Assistance":
|
228 |
-
guide_chat_history.append((
|
229 |
-
"I'm building a Streamlit app to display data from a CSV file.",
|
230 |
-
"Great! Let's start by creating a new project in the workspace."
|
231 |
-
))
|
232 |
-
guide_chat_history.append((
|
233 |
-
"Create a new project called 'data_app'.",
|
234 |
-
"Okay, I've created the project 'data_app'. What would you like to name the main file?"
|
235 |
-
))
|
236 |
-
guide_chat_history.append((
|
237 |
-
"Name it 'app.py'.",
|
238 |
-
"Alright, I've added an empty 'app.py' file to the 'data_app' project. Now, let's add some code to read the CSV file."
|
239 |
-
))
|
240 |
-
guide_chat_history.append((
|
241 |
-
"Add the following code to 'app.py':\n```python\nimport pandas as pd\nimport streamlit as st\n\ndata = pd.read_csv('data.csv')\nst.write(data)\n```",
|
242 |
-
"Excellent! Now you can run this code to see the data from your CSV file in the Streamlit app."
|
243 |
-
))
|
244 |
-
elif ai_guide_level == "Partial Assistance":
|
245 |
-
guide_chat_history.append((
|
246 |
-
"I'm building a Streamlit app to display data from a CSV file.",
|
247 |
-
"That's a great project! Let me know if you need any help with specific parts of the implementation."
|
248 |
-
))
|
249 |
-
|
250 |
-
st.markdown(display_chat_history(guide_chat_history))
|
251 |
|
252 |
-
with workspace_tabs[1]:
|
253 |
-
# Tool Box Tab
|
254 |
-
st.subheader("Tool Box")
|
255 |
-
|
256 |
# Code Editor
|
257 |
st.subheader("Code Editor")
|
|
|
258 |
code = st_ace(language="python", theme="monokai", key="code_editor")
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
hints = analyze_code(code)
|
263 |
-
for hint in hints:
|
264 |
-
st.info(hint)
|
265 |
-
|
266 |
-
# Code Completion
|
267 |
-
if st.button("Get Code Completion"):
|
268 |
-
completion = get_code_completion(code)
|
269 |
-
st.code(completion, language="python")
|
270 |
-
|
271 |
-
# Code Linting
|
272 |
-
if st.button("Lint Code"):
|
273 |
-
lint_messages = lint_code(code)
|
274 |
-
for message in lint_messages:
|
275 |
-
st.warning(message)
|
276 |
-
|
277 |
-
# Code Formatting
|
278 |
-
if st.button("Format Code"):
|
279 |
-
formatted_code = format_code(code)
|
280 |
-
st.code(formatted_code, language="python")
|
281 |
|
282 |
-
|
283 |
-
|
284 |
-
st.
|
285 |
-
|
|
|
286 |
|
287 |
-
|
288 |
-
|
289 |
-
if st.button("Create Project"):
|
290 |
-
result = workspace_interface(new_project)
|
291 |
-
st.success(result)
|
292 |
-
|
293 |
-
# Add code to project
|
294 |
-
project_name = st.selectbox("Select project", list(st.session_state.workspace_projects.keys()))
|
295 |
-
file_name = st.text_input("Enter file name:")
|
296 |
-
code_to_add = st.text_area("Enter code:")
|
297 |
-
if st.button("Add Code"):
|
298 |
-
result = add_code_to_workspace(project_name, code_to_add, file_name)
|
299 |
-
st.success(result)
|
300 |
|
301 |
if __name__ == "__main__":
|
302 |
main()
|
|
|
21 |
st.error("Hugging Face API key not found. Please make sure it is set in the secrets.")
|
22 |
|
23 |
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/0shotTest"
|
24 |
+
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), 'user_projects'))
|
|
|
25 |
AVAILABLE_CODE_GENERATIVE_MODELS = ["bigcode/starcoder", "Salesforce/codegen-350M-mono", "microsoft/CodeGPT-small"]
|
26 |
|
27 |
+
# Create PROJECT_ROOT if it doesn't exist
|
28 |
+
if not os.path.exists(PROJECT_ROOT):
|
29 |
+
os.makedirs(PROJECT_ROOT)
|
30 |
+
|
31 |
# Global state management
|
32 |
if 'chat_history' not in st.session_state:
|
33 |
st.session_state.chat_history = []
|
|
|
35 |
st.session_state.terminal_history = []
|
36 |
if 'workspace_projects' not in st.session_state:
|
37 |
st.session_state.workspace_projects = {}
|
38 |
+
if 'current_project' not in st.session_state:
|
39 |
+
st.session_state.current_project = None
|
40 |
|
41 |
# AI Guide Toggle
|
42 |
ai_guide_level = st.sidebar.radio("AI Guide Level", ["Full Assistance", "Partial Assistance", "No Assistance"])
|
|
|
45 |
code_generator_tokenizer = AutoTokenizer.from_pretrained("microsoft/CodeGPT-small-py", clean_up_tokenization_spaces=True)
|
46 |
code_generator = pipeline("text-generation", model="microsoft/CodeGPT-small-py", tokenizer=code_generator_tokenizer)
|
47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
class AIAgent:
|
49 |
+
def __init__(self, name: str, description: str, skills: List[str]):
|
50 |
self.name = name
|
51 |
self.description = description
|
52 |
self.skills = skills
|
|
|
|
|
53 |
|
54 |
def generate_agent_response(self, prompt: str) -> str:
|
55 |
+
# For now, we'll use a simple response. In a real implementation, you'd use a more sophisticated model.
|
56 |
+
return f"Agent {self.name} responding to: {prompt}"
|
57 |
|
58 |
def create_agent_prompt(self) -> str:
|
59 |
skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
|
|
|
64 |
"""
|
65 |
return agent_prompt
|
66 |
|
67 |
+
def create_project(self, project_name: str) -> str:
|
68 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
69 |
+
if not os.path.exists(project_path):
|
70 |
+
os.makedirs(project_path)
|
71 |
+
st.session_state.workspace_projects[project_name] = {'files': []}
|
72 |
+
return f"Project '{project_name}' created successfully."
|
73 |
+
else:
|
74 |
+
return f"Project '{project_name}' already exists."
|
75 |
+
|
76 |
+
def add_file_to_project(self, project_name: str, file_name: str, content: str) -> str:
|
77 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
78 |
+
if not os.path.exists(project_path):
|
79 |
+
return f"Project '{project_name}' does not exist."
|
80 |
+
|
81 |
+
file_path = os.path.join(project_path, file_name)
|
82 |
+
with open(file_path, "w") as file:
|
83 |
+
file.write(content)
|
84 |
+
st.session_state.workspace_projects[project_name]['files'].append(file_name)
|
85 |
+
return f"File '{file_name}' added to project '{project_name}'."
|
86 |
+
|
87 |
+
def modify_file_in_project(self, project_name: str, file_name: str, content: str) -> str:
|
88 |
+
project_path = os.path.join(PROJECT_ROOT, project_name)
|
89 |
+
file_path = os.path.join(project_path, file_name)
|
90 |
+
if not os.path.exists(file_path):
|
91 |
+
return f"File '{file_name}' does not exist in project '{project_name}'."
|
92 |
+
|
93 |
+
with open(file_path, "w") as file:
|
94 |
+
file.write(content)
|
95 |
+
return f"File '{file_name}' in project '{project_name}' has been modified."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
+
# Initialize some example agents
|
98 |
+
example_agents = [
|
99 |
+
AIAgent("WebDev Wizard", "Full-stack web development expert", ["HTML", "CSS", "JavaScript", "React", "Node.js"]),
|
100 |
+
AIAgent("Data Scientist", "Machine learning and data analysis specialist", ["Python", "Pandas", "Scikit-learn", "TensorFlow"]),
|
101 |
+
AIAgent("DevOps Guru", "Infrastructure and deployment expert", ["Docker", "Kubernetes", "AWS", "CI/CD"])
|
102 |
+
]
|
103 |
|
104 |
def main():
|
105 |
+
st.title("AI-Guided Workspace")
|
106 |
+
|
107 |
+
# Sidebar for project selection and creation
|
108 |
+
st.sidebar.header("Project Management")
|
109 |
+
project_name = st.sidebar.text_input("Enter project name:")
|
110 |
+
if st.sidebar.button("Create Project"):
|
111 |
+
result = example_agents[0].create_project(project_name)
|
112 |
+
st.sidebar.write(result)
|
113 |
+
|
114 |
+
projects = list(st.session_state.workspace_projects.keys())
|
115 |
+
selected_project = st.sidebar.selectbox("Select a project", projects, index=0 if projects else None)
|
116 |
+
if selected_project:
|
117 |
+
st.session_state.current_project = selected_project
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
+
# Main area
|
120 |
+
if st.session_state.current_project:
|
121 |
+
st.header(f"Current Project: {st.session_state.current_project}")
|
122 |
|
123 |
+
# Chat with AI Agent
|
124 |
+
st.subheader("Chat with AI Agent")
|
|
|
125 |
user_input = st.text_input("Enter your message:")
|
126 |
+
if st.button("Send"):
|
127 |
+
agent_response = example_agents[0].generate_agent_response(user_input)
|
128 |
+
st.session_state.chat_history.append((user_input, agent_response))
|
|
|
129 |
|
130 |
# Display chat history
|
131 |
+
for user, agent in st.session_state.chat_history:
|
132 |
+
st.text(f"You: {user}")
|
133 |
+
st.text(f"Agent: {agent}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
|
|
|
|
|
|
|
|
135 |
# Code Editor
|
136 |
st.subheader("Code Editor")
|
137 |
+
file_name = st.text_input("File name:")
|
138 |
code = st_ace(language="python", theme="monokai", key="code_editor")
|
139 |
+
if st.button("Save File"):
|
140 |
+
result = example_agents[0].add_file_to_project(st.session_state.current_project, file_name, code)
|
141 |
+
st.write(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
|
143 |
+
# Display project files
|
144 |
+
st.subheader("Project Files")
|
145 |
+
if st.session_state.current_project in st.session_state.workspace_projects:
|
146 |
+
for file in st.session_state.workspace_projects[st.session_state.current_project]['files']:
|
147 |
+
st.text(file)
|
148 |
|
149 |
+
else:
|
150 |
+
st.write("Please create or select a project to get started.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
|
152 |
if __name__ == "__main__":
|
153 |
main()
|