Spaces:
Paused
Paused
Update app.py
Browse files160 unmodified lines161162163164165166167160 unmodified linesif agent_prompt is None:return f"Agent {agent_name} not found."model_name = "MaziyarPanahi/Codestral-22B-v0.1-GGUF"try:generator = pipeline("text-generation", model=model_name)generator.tokenizer.pad_token = generator.tokenizer.eos_token160 unmodified lines161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627160 unmodified linesif agent_prompt is None:return f"Agent {agent_name} not found."model_name = "MaziyarPanahi/Codestral-22B-v0.1-GGUF"import osimport subprocessimport streamlit as stfrom transformers import pipeline, AutoModelForCausalLM, AutoTokenizerimport blackfrom pylint import lintfrom io import StringIOHUGGING_FACE_REPO_URL = "https://huggingface.co/spaces/acecalisto3/DevToolKit"PROJECT_ROOT = "projects"AGENT_DIRECTORY = "agents"# Global state to manage communication between Tool Box and Workspace Chat Appif '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': {}}class AIAgent:def __init__(self, name, description, skills):self.name = nameself.description = descriptionself.skills = skillsdef 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_promptdef autonomous_build(self, chat_history, workspace_projects):"""Autonomous build logic that continues based on the state of chat history and 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_stepdef save_agent_to_file(agent):"""Saves the agent's prompt to a file locally and then commits to the Hugging Face repository."""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):"""Loads an agent prompt from a file."""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_promptelse:return Nonedef 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 agentdef 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."# Load the GPT-2 model which is compatible with AutoModelForCausalLMmodel_name = "gpt2"try:model = AutoModelForCausalLM.from_pretrained(model_name)tokenizer = AutoTokenizer.from_pretrained(model_name)generator = pipeline("text-generation", model=model, tokenizer=tokenizer)except EnvironmentError as e:return f"Error loading model: {e}"# Combine the agent prompt with user inputcombined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:"# Truncate input text to avoid exceeding the model's maximum lengthmax_input_length = 900input_ids = tokenizer.encode(combined_input, return_tensors="pt")if input_ids.shape[1] > max_input_length:input_ids = input_ids[:, :max_input_length]# Generate chatbot responseoutputs = model.generate(input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True, pad_token_id=tokenizer.eos_token_id # Set pad_token_id to eos_token_id)response = tokenizer.decode(outputs[0], skip_special_tokens=True)return responsedef 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_namecommit_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.stdoutreturn result.stdoutelse:st.session_state.current_state['toolbox']['terminal_output'] = result.stderrreturn result.stderrdef 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]# ... [rest of the translate_code function, but remove the OpenAI API call and replace it with your own logic] ...def generate_code(code_idea):# Replace this with a call to a Hugging Face model or your own logic# For example, using a text-generation pipeline:generator = pipeline('text-generation', model='gpt4o')generated_code = generator(code_idea, max_length=10000, num_return_sequences=1)[0]['generated_text']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}"}]st.session_state.current_state['toolbox']['generated_code'] = generated_codereturn generated_codedef translate_code(code, input_language, output_language):# Define a dictionary to map programming languages to their corresponding file extensionslanguage_extensions = {"Python": "py","JavaScript": "js","Java": "java","C++": "cpp","C#": "cs","Ruby": "rb","Go": "go","PHP": "php","Swift": "swift","TypeScript": "ts",}# Add code to handle edge cases such as invalid input and unsupported programming languagesif 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 extensionsinput_extension = language_extensions[input_language]output_extension = language_extensions[output_language]# Translate the code using the OpenAI APIprompt = 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()# Return the translated codetranslated_code = response.choices[0].message['content'].strip()st.session_state.current_state['toolbox']['translated_code'] = translated_codereturn translated_codedef 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_codereturn generated_codedef 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}")breakdef interact_with_web_interface(agent, api_key, url, payload):"""Interacts with a web interface using the provided API key and payload.Args:agent: The AIAgent instance.api_key: The API key for the web interface.url: The URL of the web interface.payload: The payload to send to the web interface.Returns:The response from the web interface."""# Use the agent's knowledge to determine the appropriate HTTP method and headers.http_method = agent.get_http_method(url)headers = agent.get_headers(url)# Add the API key to the headers.headers["Authorization"] = f"Bearer {api_key}"# Send the request to the web interface.response = requests.request(http_method, url, headers=headers, json=payload)# Return the response.return responsedef get_http_method(url):"""Determines the appropriate HTTP method for the given URL.Args:url: The URL of the web interface.Returns:The HTTP method (e.g., "GET", "POST", "PUT", "DELETE")."""# Use the agent's knowledge to determine the HTTP method.# For example, the agent might know that the URL is for a REST API endpoint that supports CRUD operations.return "GET"def get_headers(url):"""Determines the appropriate headers for the given URL.Args:url: The URL of the web interface.Returns:A dictionary of headers."""# Use the agent's knowledge to determine the headers.# For example, the agent might know that the web interface requires an "Authorization" header with an API key.return {"Content-Type": "application/json"}# ... (rest of the code)if app_mode == "Toolbox":# Streamlit Appst.title("AI Agent Creator")# Sidebar navigationst.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 Creatorst.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 Boxst.header("AI-Powered Tools")# Chat Interfacest.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_namechat_input = " ".join(chat_input.split(" ")[1:]) # Remove agent_name from inputchat_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 Interfacest.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 Interfacest.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 Toolst.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 Toolst.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}")# Text Translation Tool (Code Translation)st.subheader("Translate Code")code_to_translate = st.text_area("Enter code to translate:")input_language = st.text_input("Enter input language (e.g. 'Python'):")output_language = st.text_input("Enter output language (e.g. 'JavaScript'):")if st.button("Translate Code"):translated_code = translate_code(code_to_translate, input_language, output_language)st.code(translated_code, language=output_language.lower())# Code Generationst.subheader("Code Generation")code_idea = st.text_input("Enter your code idea:")if st.button("Generate Code"):generated_code = generate_code(code_idea)st.code(generated_code, language="python")# Display Preset Commandsst.subheader("Preset Commands")preset_commands = {"Create a new project": "create_project('project_name')","Add code to workspace": "add_code_to_workspace('project_name', 'code', 'file_name')","Run terminal command": "terminal_interface('command', 'project_name')","Generate code": "generate_code('code_idea')","Summarize text": "summarize_text('text')","Analyze sentiment": "sentiment_analysis('text')","Translate code": "translate_code('code', 'source_language', 'target_language')",}for command_name, command in preset_commands.items():st.write(f"{command_name}: `{command}`")elif app_mode == "Workspace Chat App":# Workspace Chat Appst.header("Workspace Chat App")# Project Workspace Creationst.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)# Add Code to Workspacest.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)# Terminal Interface with Project Contextst.subheader("Terminal (Workspace Context)")terminal_input = st.text_input("Enter a command within the workspace:")if st.button("Run Command"):terminal_output = terminal_interface(terminal_input, project_name)st.code(terminal_output, language="bash")# Chat Interface for Guidancest.subheader("Chat with CodeCraft for Guidance")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"CodeCraft: {chat_response}")# Display Chat Historyst.subheader("Chat History")for user_input, response in st.session_state.chat_history:st.write(f"User: {user_input}")st.write(f"CodeCraft: {response}")# Display Terminal Historyst.subheader("Terminal History")for command, output in st.session_state.terminal_history:st.write(f"Command: {command}")st.code(output, language="bash")# Display Projects and Filesst.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}")try:generator = pipeline("text-generation", model=model_name)generator.tokenizer.pad_token = generator.tokenizer.eos_token
app.py+461-1