MistriDevLab / app.py
acecalisto3's picture
Update app.py
8173591 verified
raw
history blame
14.4 kB
import os
import subprocess
import streamlit as st
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
import openai
# Constants
HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"
PROJECT_ROOT = "projects"
AGENT_DIRECTORY = "agents"
# Initialize session state
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if 'terminal_history' not in st.session_state:
st.session_state.terminal_history = []
if 'workspace_projects' not in st.session_state:
st.session_state.workspace_projects = {}
if 'available_agents' not in st.session_state:
st.session_state.available_agents = []
if 'current_state' not in st.session_state:
st.session_state.current_state = {
'toolbox': {},
'workspace_chat': {}
}
# AI Agent class
class AIAgent:
def __init__(self, name, description, skills):
self.name = name
self.description = description
self.skills = skills
def create_agent_prompt(self):
skills_str = '\n'.join([f"* {skill}" for skill in self.skills])
agent_prompt = f"""
As an elite expert developer, my name is {self.name}. I possess a comprehensive understanding of the following areas:
{skills_str}
I am confident that I can leverage my expertise to assist you in developing and deploying cutting-edge web applications. Please feel free to ask any questions or present any challenges you may encounter.
"""
return agent_prompt
def autonomous_build(self, chat_history, workspace_projects):
summary = "Chat History:\n" + "\n".join([f"User: {u}\nAgent: {a}" for u, a in chat_history])
summary += "\n\nWorkspace Projects:\n" + "\n".join([f"{p}: {details}" for p, details in workspace_projects.items()])
next_step = "Based on the current state, the next logical step is to implement the main application logic."
return summary, next_step
# Functions for agent management
def save_agent_to_file(agent):
if not os.path.exists(AGENT_DIRECTORY):
os.makedirs(AGENT_DIRECTORY)
file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt")
config_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}Config.txt")
with open(file_path, "w") as file:
file.write(agent.create_agent_prompt())
with open(config_path, "w") as file:
file.write(f"Agent Name: {agent.name}\nDescription: {agent.description}")
st.session_state.available_agents.append(agent.name)
commit_and_push_changes(f"Add agent {agent.name}")
def load_agent_prompt(agent_name):
file_path = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt")
if os.path.exists(file_path):
with open(file_path, "r") as file:
agent_prompt = file.read()
return agent_prompt
else:
return None
def create_agent_from_text(name, text):
skills = text.split('\n')
agent = AIAgent(name, "AI agent created from text input.", skills)
save_agent_to_file(agent)
return agent.create_agent_prompt()
# OpenAI GPT-3 API setup for text generation
openai.api_key = st.secrets["OPENAI_API_KEY"]
# Initialize the Hugging Face model and tokenizer
model_name = "gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
generator = pipeline('text-generation', model=model, tokenizer=tokenizer)
# Tool Box UI elements
def toolbox():
st.header("Tool Box")
# List available agents
for agent in st.session_state.available_agents:
st.markdown(f"### {agent}")
st.write(agent.description)
if st.button(f'Chat with {agent}'):
chat_with_agent(agent)
# Add new agents
if st.session_state['toolbox'].get('new_agent') is None:
st.session_state['toolbox']['new_agent'] = {}
st.text_input("Agent Name", key='name', on_change=update_agent)
st.text_area("Agent Description", key='description', on_change=update_agent)
st.text_input("Skills (comma-separated)", key='skills', on_change=update_agent)
if st.button('Create New Agent'):
skills = [s.strip() for s in st.session_state['toolbox']['new_agent'].get('skills', '').split(',')]
new_agent = AIAgent(st.session_state['toolbox']['new_agent'].get('name'),
st.session_state['toolbox']['new_agent'].get('description'), skills)
st.session_state.available_agents.append(new_agent)
def update_agent():
st.session_state['toolbox']['new_agent'] = {
'name': st.session_state.name,
'description': st.session_state.description,
'skills': st.session_state.skills
}
def chat_with_agent(agent_name):
st.subheader(f"Chat with {agent_name}")
chat_input = st.text_area("Enter your message:")
if st.button("Send"):
chat_response = chat_interface_with_agent(chat_input, agent_name)
st.session_state.chat_history.append((chat_input, chat_response))
st.write(f"{agent_name}: {chat_response}")
# Workspace UI elements
def workspace():
st.header("Workspace")
# Project selection and interaction
for project, details in st.session_state.workspace_projects.items():
st.write(f"Project: {project}")
for file in details['files']:
st.write(f" - {file}")
if st.button('Add New Project'):
new_project = {'name': '', 'description': '', 'files': []}
st.session_state.workspace_projects[new_project['name']] = new_project
# Main function to display the app
def main():
toolbox()
workspace()
if __name__ == "__main__":
main()
# Additional functionalities
def commit_and_push_changes(commit_message):
commands = [
"git add .",
f"git commit -m '{commit_message}'",
"git push"
]
for command in commands:
result = subprocess.run(command, shell=True, capture_output=True, text=True)
if result.returncode != 0:
st.error(f"Error executing command '{command}': {result.stderr}")
break
def chat_interface_with_agent(input_text, agent_name):
agent_prompt = load_agent_prompt(agent_name)
if agent_prompt is None:
return f"Agent {agent_name} not found."
combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"
max_input_length = 900
input_ids = tokenizer.encode(combined_input, return_tensors="pt")
if input_ids.shape[1] > max_input_length:
input_ids = input_ids[:, :max_input_length]
outputs = model.generate(input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True, pad_token_id=tokenizer.eos_token_id)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
return response
def workspace_interface(project_name):
project_path = os.path.join(PROJECT_ROOT, project_name)
if not os.path.exists(PROJECT_ROOT):
os.makedirs(PROJECT_ROOT)
if not os.path.exists(project_path):
os.makedirs(project_path)
st.session_state.workspace_projects[project_name] = {"files": []}
st.session_state.current_state['workspace_chat']['project_name'] = project_name
commit_and_push_changes(f"Create project {project_name}")
return f"Project {project_name} created successfully."
else:
return f"Project {project_name} already exists."
def add_code_to_workspace(project_name, code, file_name):
project_path = os.path.join(PROJECT_ROOT, project_name)
if os.path.exists(project_path):
file_path = os.path.join(project_path, file_name)
with open(file_path, "w") as file:
file.write(code)
st.session_state.workspace_projects[project_name]["files"].append(file_name)
st.session_state.current_state['workspace_chat']['added_code'] = {"file_name": file_name, "code": code}
commit_and_push_changes(f"Add code to {file_name} in project {project_name}")
return f"Code added to {file_name} in project {project_name} successfully."
else:
return f"Project {project_name} does not exist."
def terminal_interface(command, project_name=None):
if project_name:
project_path = os.path.join(PROJECT_ROOT, project_name)
if not os.path.exists(project_path):
return f"Project {project_name} does not exist."
result = subprocess.run(command, cwd=project_path, shell=True, capture_output=True, text=True)
else:
result = subprocess.run(command, shell=True, capture_output=True, text=True)
if result.returncode == 0:
st.session_state.current_state['toolbox']['terminal_output'] = result.stdout
return result.stdout
else:
st.session_state.current_state['toolbox']['terminal_output'] = result.stderr
return result.stderr
def summarize_text(text):
summarizer = pipeline("summarization")
summary = summarizer(text, max_length=50, min_length=25, do_sample=False)
st.session_state.current_state['toolbox']['summary'] = summary[0]['summary_text']
return summary[0]['summary_text']
def sentiment_analysis(text):
analyzer = pipeline("sentiment-analysis")
sentiment = analyzer(text)
st.session_state.current_state['toolbox']['sentiment'] = sentiment[0]
return sentiment[0]
def generate_code(code_idea):
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an expert software developer."},
{"role": "user", "content": f"Generate a Python code snippet for the following idea:\n\n{code_idea}"}
]
)
generated_code = response.choices[0].message['content'].strip()
st.session_state.current_state['toolbox']['generated_code'] = generated_code
return generated_code
def translate_code(code, input_language, output_language):
language_extensions = {
"Python": ".py",
"JavaScript": ".js",
# Add more languages and their extensions here
}
if input_language not in language_extensions:
raise ValueError(f"Invalid input language: {input_language}")
if output_language not in language_extensions:
raise ValueError(f"Invalid output language: {output_language}")
prompt = f"Translate this code from {input_language} to {output_language}:\n\n{code}"
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an expert software developer."},
{"role": "user", "content": prompt}
]
)
translated_code = response.choices[0].message['content'].strip()
st.session_state.current_state['toolbox']['translated_code'] = translated_code
return translated_code
# Streamlit App
st.title("AI Agent Creator")
# Sidebar navigation
st.sidebar.title("Navigation")
app_mode = st.sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"])
if app_mode == "AI Agent Creator":
# AI Agent Creator
st.header("Create an AI Agent from Text")
st.subheader("From Text")
agent_name = st.text_input("Enter agent name:")
text_input = st.text_area("Enter skills (one per line):")
if st.button("Create Agent"):
agent_prompt = create_agent_from_text(agent_name, text_input)
st.success(f"Agent '{agent_name}' created and saved successfully.")
st.session_state.available_agents.append(agent_name)
elif app_mode == "Tool Box":
# Tool Box
st.header("AI-Powered Tools")
# Chat Interface
st.subheader("Chat with CodeCraft")
chat_input = st.text_area("Enter your message:")
if st.button("Send"):
if chat_input.startswith("@"):
agent_name = chat_input.split(" ")[0][1:] # Extract agent_name from @agent_name
chat_input = " ".join(chat_input.split(" ")[1:]) # Remove agent_name from input
chat_response = chat_interface_with_agent(chat_input, agent_name)
st.session_state.chat_history.append((chat_input, chat_response))
st.write(f"{agent_name}: {chat_response}")
# Code Generation
st.subheader("Generate Code")
code_idea = st.text_area("Enter your code idea:")
if st.button("Generate Code"):
generated_code = generate_code(code_idea)
st.code(generated_code, language='python')
# Code Translation
st.subheader("Translate Code")
code = st.text_area("Enter your code:")
input_language = st.selectbox("Input Language", ["Python", "JavaScript"])
output_language = st.selectbox("Output Language", ["Python", "JavaScript"])
if st.button("Translate Code"):
translated_code = translate_code(code, input_language, output_language)
st.code(translated_code, language=output_language.lower())
# Summarization
st.subheader("Summarize Text")
text_to_summarize = st.text_area("Enter text to summarize:")
if st.button("Summarize"):
summary = summarize_text(text_to_summarize)
st.write(summary)
# Sentiment Analysis
st.subheader("Sentiment Analysis")
text_to_analyze = st.text_area("Enter text for sentiment analysis:")
if st.button("Analyze Sentiment"):
sentiment = sentiment_analysis(text_to_analyze)
st.write(sentiment)
elif app_mode == "Workspace Chat App":
# Workspace Chat App
st.header("Workspace Chat App")
# Project Management
st.subheader("Manage Projects")
project_name = st.text_input("Enter project name:")
if st.button("Create Project"):
project_message = workspace_interface(project_name)
st.success(project_message)
# Add Code to Project
st.subheader("Add Code to Project")
project_name_for_code = st.text_input("Enter project name for code:")
code_content = st.text_area("Enter code content:")
file_name = st.text_input("Enter file name:")
if st.button("Add Code"):
add_code_message = add_code_to_workspace(project_name_for_code, code_content, file_name)
st.success(add_code_message)
# Terminal Interface
st.subheader("Terminal Interface")
terminal_command = st.text_area("Enter terminal command:")
project_name_for_terminal = st.text_input("Enter project name for terminal (optional):")
if st.button("Run Command"):
terminal_output = terminal_interface(terminal_command, project_name_for_terminal)
st.text(terminal_output)