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