Spaces:
Sleeping
Sleeping
import streamlit as st | |
import os | |
import subprocess | |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer | |
import black | |
from pylint import lint | |
from io import StringIO | |
import sys | |
PROJECT_ROOT = "projects" | |
AGENT_DIRECTORY = "agents" | |
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 = [] | |
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 that continues based on the state of chat history and workspace projects. | |
""" | |
# Example logic: Generate a summary of chat history and workspace state | |
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()]) | |
# Example: Generate the next logical step in the project | |
next_step = "Based on the current state, the next logical step is to implement the main application logic." | |
return summary, next_step | |
def save_agent_to_file(agent): | |
"""Saves the agent's prompt to a file.""" | |
if not os.path.exists(AGENT_DIRECTORY): | |
os.makedirs(AGENT_DIRECTORY) | |
file_path = os.path.join(AGENT_DIRECTORY, f"{agent.name}.txt") | |
with open(file_path, "w") as file: | |
file.write(agent.create_agent_prompt()) | |
st.session_state.available_agents.append(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_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() | |
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." | |
model_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 input | |
combined_input = f"{agent_prompt}\n\nUser: {input_text}\nAgent:" | |
# Truncate input text to avoid exceeding the model's maximum length | |
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] | |
# Generate chatbot response | |
outputs = model.generate( | |
input_ids, max_new_tokens=50, num_return_sequences=1, do_sample=True | |
) | |
response = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
return response | |
def terminal_interface(command, project_name=None): | |
if project_name: | |
project_path = os.path.join(PROJECT_ROOT, project_name) | |
result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=project_path) | |
else: | |
result = subprocess.run(command, shell=True, capture_output=True, text=True) | |
return result.stdout | |
def code_editor_interface(code): | |
formatted_code = black.format_str(code, mode=black.FileMode()) | |
pylint_output = lint.Run([formatted_code], do_exit=False) | |
pylint_output_str = StringIO() | |
pylint_output.linter.reporter.write_messages(pylint_output_str) | |
return formatted_code, pylint_output_str.getvalue() | |
def summarize_text(text): | |
summarizer = pipeline("summarization") | |
summary = summarizer(text, max_length=130, min_length=30, do_sample=False) | |
return summary[0]['summary_text'] | |
def sentiment_analysis(text): | |
analyzer = pipeline("sentiment-analysis") | |
result = analyzer(text) | |
return result[0]['label'] | |
def translate_code(code, source_language, target_language): | |
# Placeholder for translation logic | |
return f"Translated {source_language} code to {target_language}." | |
def generate_code(idea): | |
# Placeholder for code generation logic | |
return f"Generated code based on the idea: {idea}." | |
def workspace_interface(project_name): | |
project_path = os.path.join(PROJECT_ROOT, project_name) | |
if not os.path.exists(project_path): | |
os.makedirs(project_path) | |
st.session_state.workspace_projects[project_name] = {'files': []} | |
return f"Project '{project_name}' created successfully." | |
def add_code_to_workspace(project_name, code, file_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." | |
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) | |
return f"Code added to '{file_name}' in project '{project_name}'." | |
def chat_interface(input_text): | |
# Placeholder for chat interface logic | |
return f"Chatbot response: {input_text}" | |
st.title("AI Agent Creator") | |
sidebar = st.sidebar | |
sidebar.title("Navigation") | |
app_mode = sidebar.selectbox("Choose the app mode", ["AI Agent Creator", "Tool Box", "Workspace Chat App"]) | |
if app_mode == "AI Agent Creator": | |
st.header("Create an AI Agent from Text") | |
subheader = st.subheader | |
agent_name = subheader("Enter agent name:") | |
text_input = subheader("Enter skills (one per line):") | |
if st.button("Create Agent"): | |
agent_prompt = create_agent_from_text(agent_name, text_input) |