import subprocess import streamlit as st from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer import black from pylint import lint from io import StringIO import os import json from streamlit_ace import st_ace from agent import ( AppType, createLlamaPrompt, createSpace, isPythonOrGradioAppPrompt, isReactAppPrompt, isStreamlitAppPrompt, generateFiles, ) import importlib # Dynamically import the Code symbol from the agent module code_module = importlib.import_module('agent.Code') Code = getattr(code_module, 'Code') # Set Hugging Face repository URL and project root path HUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/Mistri" PROJECT_ROOT = "projects" AGENT_DIRECTORY = "agents" # Global state for session management 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': {} } # Load Hugging Face models for code generation, translation, and conversation try: code_generator = pipeline("text-generation", model="Salesforce/codegen-350M-mono") translator = pipeline("translation_xx_to_yy", model="Helsinki-NLP/opus-mt-en-fr") # Replace with appropriate language pair conversational_model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium") conversational_tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium") conversational_generator = pipeline("text-generation", model=conversational_model, tokenizer=conversational_tokenizer) except EnvironmentError as e: st.error(f"Error loading Hugging Face models: {e}") # Define AIAgent 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): """ Autonomous build logic based on chat history and workspace projects. This function analyzes the chat history and workspace projects to determine the next steps in the development process. It uses sentiment analysis to gauge the user's satisfaction and summarization to extract key information. Args: chat_history (list): A list of tuples containing user input and agent responses. workspace_projects (dict): A dictionary of projects and their associated files. Returns: tuple: A tuple containing a summary of the current state and the suggested next step. """ 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}: {', '.join(ws_projects.keys())}" for p, ws_projects in workspace_projects.items()]) sentiment_analyzer = pipeline("sentiment-analysis") sentiment_output = sentiment_analyzer(summary)[0] # Use a Hugging Face model for more advanced logic summarizer = pipeline("summarization") next_step = summarizer(summary, max_length=50, min_length=25, do_sample=False)[0]['summary_text'] return summary, next_step # Function to save an agent's prompt to a file and commit to the Hugging Face repository def save_agent_to_file(agent): """Saves the agent's prompt to a file locally and then commits to the Hugging Face repository.""" agents_path = os.path.join(PROJECT_ROOT, AGENT_DIRECTORY) if not os.path.exists(agents_path): os.makedirs(agents_path) agent_file = os.path.join(agents_path, f"{agent.name}.txt") config_file = os.path.join(agents_path, f"{agent.name}Config.txt") with open(agent_file, "w") as file: file.write(agent.create_agent_prompt()) with open(config_file, "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}") # Function to load an agent's prompt from a file def load_agent_prompt(agent_name): """Loads an agent prompt from a file.""" agent_file = os.path.join(AGENT_DIRECTORY, f"{agent_name}.txt") if os.path.exists(agent_file): with open(agent_file, "r") as file: agent_prompt = file.read() return agent_prompt else: return None # Function to create an agent from text input 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() # Chat interface using a selected agent def chat_interface_with_agent(input_text, agent_name): """ Provides a chat interface using a selected AI agent. Loads the agent's prompt and uses a conversational model to generate responses. Args: input_text (str): The user's input text. agent_name (str): The name of the selected AI agent. Returns: str: The AI agent's response. """ agent_prompt = load_agent_prompt(agent_name) if agent_prompt is None: return f"Agent {agent_name} not found." # Combine agent prompt with user input combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:" # Generate chatbot response chatbot_response = conversational_generator(combined_input, max_length=150, min_length=30, do_sample=True)[0]['generated_text'] return chatbot_response # Chat interface (default) def chat_interface(input_text): """ Provides a general chat interface using a conversational model. Args: input_text (str): The user's input text. Returns: str: The chatbot's response. """ # Generate response response = conversational_generator(input_text, max_length=150, min_length=30, do_sample=True)[0]['generated_text'] return response # Workspace interface for creating projects def workspace_interface(project_name): """ Creates a new project workspace. Args: project_name (str): The name of the project. Returns: str: A message indicating the status of the project creation. """ 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): 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." # Function to add code to the workspace def add_code_to_workspace(project_name, code, file_name): """ Adds code to a specified file in a project workspace. Args: project_name (str): The name of the project. code (str): The code to be added. file_name (str): The name of the file. Returns: str: A message indicating the status of the code addition. """ 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." # Terminal interface with optional project context def terminal_interface(command, project_name=None): """ Executes a terminal command with optional project context. Args: command (str): The terminal command to execute. project_name (str, optional): The name of the project to execute the command in. Defaults to None. Returns: str: The output of the terminal command. """ 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 # Code editor interface for formatting and linting def code_editor_interface(code): """ Provides a code editor interface with formatting and linting capabilities. Args: code (str): The code to be edited. Returns: tuple: A tuple containing the formatted code and any linting messages. """ try: formatted_code = black.format_str(code, mode=black.FileMode()) except black.NothingChanged: formatted_code = code result = StringIO() sys.stdout = result sys.stderr = result pylint_stdout, pylint_stderr = lint.py_run(code, return_std=True) sys.stdout = sys.stdout sys.stderr = sys.stderr lint_message = pylint_stdout.getvalue() + pylint_stderr.getvalue() st.session_state.current_state['toolbox']['formatted_code'] = formatted_code st.session_state.current_state['toolbox']['lint_message'] = lint_message return formatted_code, lint_message # Function to summarize text using a summarization pipeline def summarize_text(text): """ Summarizes a given text using a Hugging Face summarization pipeline. Args: text (str): The text to be summarized. Returns: str: The summarized 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'] # Function to perform sentiment analysis using a sentiment analysis pipeline def sentiment_analysis(text): """ Performs sentiment analysis on a given text using a Hugging Face sentiment analysis pipeline. Args: text (str): The text to be analyzed. Returns: dict: The sentiment analysis result. """ analyzer = pipeline("sentiment-analysis") sentiment = analyzer(text) st.session_state.current_state['toolbox']['sentiment'] = sentiment[0] return sentiment[0] # Function to translate code using the Hugging Face API def translate_code(code, input_language, output_language): """ Translates code from one programming language to another using a Hugging Face translation pipeline. Args: code (str): The code to be translated. input_language (str): The source programming language. output_language (str): The target programming language. Returns: str: The translated code. """ # Define a dictionary to map programming languages to their corresponding file extensions language_extensions = { "Python": ".py", "JavaScript": ".js", "C++": ".cpp", "Java": ".java", # Add more languages and extensions as needed } # Add code to handle edge cases such as invalid input and unsupported programming languages 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}") # Use the dictionary to map the input and output languages to their corresponding file extensions input_extension = language_extensions[input_language] output_extension = language_extensions[output_language] # Translate the code using the Hugging Face API translated_code = translator(code, max_length=1024)[0]['translation_text'] # Return the translated code st.session_state.current_state['toolbox']['translated_code'] = translated_code return translated_code # Function to generate code based on a code idea using the Hugging Face API def generate_code(code_idea): """ Generates code based on a given code idea using a Hugging Face code generation pipeline. Args: code_idea (str): The code idea or description. Returns: str: The generated code. """ # Generate code using the Hugging Face API generated_code = code_generator(f"python\n{code_idea}\n", max_length=512)[0]['generated_text'] st.session_state.current_state['toolbox']['generated_code'] = generated_code return generated_code # Function to commit and push changes to the Hugging Face repository def commit_and_push_changes(commit_message): """Commits and pushes changes to the Hugging Face repository.""" 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 # 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"]) # AI Agent Creator if app_mode == "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) # Tool Box elif app_mode == "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:] chat_input = " ".join(chat_input.split(" ")[1:]) chat_response = chat_interface_with_agent(chat_input, agent_name) else: chat_response = chat_interface(chat_input) st.session_state.chat_history.append((chat_input, chat_response)) st.write(f"CodeCraft: {chat_response}") # Terminal Interface st.subheader("Terminal") terminal_input = st.text_input("Enter a command:") if st.button("Run"): terminal_output = terminal_interface(terminal_input) st.session_state.terminal_history.append((terminal_input, terminal_output)) st.code(terminal_output, language="bash") # Code Editor Interface st.subheader("Code Editor") code_editor = st.text_area("Write your code:", height=300) if st.button("Format & Lint"): formatted_code, lint_message = code_editor_interface(code_editor) st.code(formatted_code, language="python") st.info(lint_message) # Text Summarization Tool 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(f"Summary: {summary}") # Sentiment Analysis Tool st.subheader("Sentiment Analysis") sentiment_text = st.text_area("Enter text for sentiment analysis:") if st.button("Analyze Sentiment"): sentiment = sentiment_analysis(sentiment_text) st.write(f"Sentiment: {sentiment}") # Workspace Chat App elif app_mode == "Workspace Chat App": st.header("Workspace Chat App") col1, col2 = st.columns(2) with col1: st.subheader("Create a New Project") project_name = st.text_input("Enter project name:") if st.button("Create Project"): workspace_status = workspace_interface(project_name) st.success(workspace_status) st.subheader("Add Code to Workspace") code_to_add = st.text_area("Enter code to add to workspace:") file_name = st.text_input("Enter file name (e.g. 'app.py'):") if st.button("Add Code"): add_code_status = add_code_to_workspace(project_name, code_to_add, file_name) st.success(add_code_status) with col2: st.subheader("Chat with AI Assistant") chat_input = st.text_area("Enter your message for guidance:") if st.button("Get Guidance"): chat_response = chat_interface(chat_input) st.session_state.chat_history.append((chat_input, chat_response)) st.write(f"AI: {chat_response}") st.subheader("Chat History") for user_input, response in st.session_state.chat_history: st.write(f"User: {user_input}") st.write(f"AI: {response}") st.subheader("Terminal History") for command, output in st.session_state.terminal_history: st.write(f"Command: {command}") st.code(output, language="bash") st.subheader("Workspace Projects") for project, details in st.session_state.workspace_projects.items(): st.write(f"Project: {project}") st.write("Files:") for file in details["files"]: st.write(f"- {file}") # Display the current state st.sidebar.subheader("Current State") st.sidebar.json(st.session_state.current_state)