import streamlit as st
import os
import json
import base64
from datetime import datetime
from pathlib import Path
import tempfile
import re
from utils import (
create_agent_template,
generate_code_from_description,
save_agent_files,
load_agent_files,
export_agent,
validate_agent_code,
get_agent_status
)
# Page configuration
st.set_page_config(
page_title="Agent Builder Pro",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better styling
st.markdown("""
""")
# Initialize session state
if 'agents' not in st.session_state:
st.session_state.agents = {}
if 'current_agent' not in st.session_state:
st.session_state.current_agent = None
if 'agent_files' not in st.session_state:
st.session_state.agent_files = {}
# Header with branding
col1, col2 = st.columns([3, 1])
with col1:
st.markdown('
🤖 Agent Builder Pro
', unsafe_allow_html=True)
st.markdown('', unsafe_allow_html=True)
with col2:
st.markdown('', unsafe_allow_html=True)
st.divider()
# Sidebar navigation
with st.sidebar:
st.markdown("### 📁 Navigation")
# Create new agent button
if st.button("➕ Create New Agent", use_container_width=True, type="primary"):
st.session_state.current_agent = None
st.session_state.agent_files = {}
st.markdown("### 📚 Your Agents")
# Load existing agents
agents_dir = Path("agents")
if agents_dir.exists():
for agent_file in agents_dir.glob("*_agent.json"):
agent_name = agent_file.stem.replace("_agent", "")
if agent_name not in st.session_state.agents:
st.session_state.agents[agent_name] = {
"created": datetime.now().isoformat(),
"modified": datetime.now().isoformat()
}
# Display agent list
if st.session_state.agents:
for agent_name, agent_info in st.session_state.agents.items():
if st.button(f"📄 {agent_name}", key=f"load_{agent_name}", use_container_width=True):
st.session_state.current_agent = agent_name
st.session_state.agent_files = load_agent_files(agent_name)
st.rerun()
st.markdown("### ⚙️ Settings")
st.info("All code generated is owned by you. Export anytime.")
# Main content area
if st.session_state.current_agent:
# Agent editing view
st.markdown(f"### 📝 Editing: {st.session_state.current_agent}")
agent_files = st.session_state.agent_files
# File selector
file_names = list(agent_files.keys())
if file_names:
selected_file = st.selectbox("Select File to Edit", file_names)
if selected_file in agent_files:
# Code editor
edited_code = st.text_area(
f"📄 {selected_file}",
value=agent_files[selected_file],
height=400,
key=f"edit_{selected_file}"
)
# Save changes
if st.button("💾 Save Changes", type="primary"):
st.session_state.agent_files[selected_file] = edited_code
save_agent_files(st.session_state.current_agent, st.session_state.agent_files)
st.success("Changes saved!")
# Validation
if selected_file.endswith(".py"):
validation_result = validate_agent_code(edited_code)
if validation_result["valid"]:
st.success("✅ Code validation passed")
else:
st.error(f"❌ {validation_result['message']}")
# Agent actions
st.markdown("### 🎯 Agent Actions")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("▶️ Test Agent", use_container_width=True):
status = get_agent_status(st.session_state.current_agent, st.session_state.agent_files)
st.json(status)
with col2:
if st.button("📦 Export Agent", use_container_width=True):
export_data = export_agent(st.session_state.current_agent, st.session_state.agent_files)
st.download_button(
label="📥 Download",
data=base64.b64decode(export_data["zip_base64"]),
file_name=f"{st.session_state.current_agent}_export.zip",
mime="application/zip"
)
with col3:
if st.button("🗑️ Delete Agent", use_container_width=True, type="secondary"):
if st.session_state.current_agent in st.session_state.agents:
del st.session_state.agents[st.session_state.current_agent]
save_agent_files(st.session_state.current_agent, {}, delete=True)
st.session_state.current_agent = None
st.session_state.agent_files = {}
st.success("Agent deleted")
st.rerun()
else:
# New agent creation view
st.markdown("### ✨ Create Your Custom Agent")
# Natural language description
agent_description = st.text_area(
"Describe your agent in natural language:",
placeholder="Example: I want an agent that can analyze CSV files, generate charts, and send email reports...",
height=150,
help="Be as detailed as possible about what your agent should do"
)
# Agent configuration
col1, col2 = st.columns(2)
with col1:
agent_name = st.text_input("Agent Name", placeholder="my_custom_agent")
agent_type = st.selectbox(
"Agent Type",
["Data Analysis", "Automation", "Chatbot", "API Integration", "Custom"]
)
with col2:
programming_language = st.selectbox("Language", ["Python", "JavaScript", "TypeScript"])
framework = st.selectbox("Framework", ["None", "LangChain", "AutoGen", "Custom"])
# Generate code button
if st.button("🚀 Generate Agent Code", type="primary", use_container_width=True):
if agent_description and agent_name:
with st.spinner("Generating agent code..."):
# Generate code from description
generated_code = generate_code_from_description(
agent_description,
agent_type,
programming_language,
framework
)
# Create agent template
agent_files = create_agent_template(
agent_name,
agent_type,
generated_code,
programming_language
)
# Save to session and disk
st.session_state.current_agent = agent_name
st.session_state.agent_files = agent_files
st.session_state.agents[agent_name] = {
"created": datetime.now().isoformat(),
"modified": datetime.now().isoformat(),
"type": agent_type,
"language": programming_language
}
save_agent_files(agent_name, agent_files)
st.success(f"✅ Agent '{agent_name}' created successfully!")
st.rerun()
else:
st.warning("Please provide both agent name and description")
# Quick templates
st.markdown("### 📋 Quick Templates")
templates = {
"Data Processor": "Process and analyze data files, generate reports",
"Email Automation": "Send automated emails based on triggers",
"API Wrapper": "Wrap external APIs with custom logic",
"Chat Assistant": "Conversational agent with memory",
"File Organizer": "Organize and categorize files automatically"
}
for template_name, template_desc in templates.items():
if st.button(f"📄 {template_name}", key=f"template_{template_name}", use_container_width=True):
st.session_state.agent_description = template_desc
st.session_state.agent_type = template_name.lower().replace(" ", "_")
# Footer
st.divider()
st.markdown("""
🔒 Your code is yours. Full ownership and control. Export anytime.
Built with anycoder • Agent Builder Pro v1.0
""", unsafe_allow_html=True)