Spaces:
Runtime error
Runtime error
File size: 7,254 Bytes
f8aca76 1cfcc0f 72ef0e0 1cfcc0f f8aca76 72ef0e0 1cfcc0f 72ef0e0 1cfcc0f 72ef0e0 7496f38 1cfcc0f 72ef0e0 1cfcc0f 72ef0e0 1cfcc0f 72ef0e0 62f80e8 f8aca76 72ef0e0 1cfcc0f 72ef0e0 f8aca76 62f80e8 f8aca76 62f80e8 72ef0e0 1cfcc0f 62f80e8 72ef0e0 f8aca76 62f80e8 72ef0e0 62f80e8 f8aca76 72ef0e0 f8aca76 1cfcc0f 72ef0e0 1f2290a 72ef0e0 1cfcc0f 72ef0e0 f8aca76 62f80e8 1cfcc0f 72ef0e0 1cfcc0f 62f80e8 1cfcc0f 72ef0e0 1cfcc0f 72ef0e0 62f80e8 1cfcc0f 62f80e8 1cfcc0f 72ef0e0 1cfcc0f 62f80e8 1cfcc0f 72ef0e0 1cfcc0f 62f80e8 1cfcc0f 62f80e8 1cfcc0f 62f80e8 1cfcc0f 62f80e8 1cfcc0f 72ef0e0 1cfcc0f 62f80e8 1cfcc0f 6b69856 1cfcc0f 72ef0e0 1cfcc0f 72ef0e0 1cfcc0f 72ef0e0 1cfcc0f f8aca76 72ef0e0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
import streamlit as st
import os
import asyncio
import time
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_chroma import Chroma
from langchain.prompts import PromptTemplate
from langchain.schema import AIMessage, HumanMessage
# ------------------------------- CONFIG -------------------------------
st.set_page_config(page_title="Intelligent Coding Agent", layout="wide")
# Inject custom CSS for full-width layout and animations
st.markdown("""
<style>
.appview-container .main .block-container {
max-width: 100%;
padding: 0 2rem;
}
.stTextArea, .stTextInput, .stButton {
width: 100% !important;
}
.stCodeBlock {
white-space: pre-wrap !important;
width: 100%;
}
.branding {
text-align: center;
font-weight: bold;
font-size: 14px;
color: #888;
padding: 10px;
}
.loader {
text-align: center;
font-size: 18px;
font-weight: bold;
animation: fadeIn 1s infinite alternate;
}
@keyframes fadeIn {
from {opacity: 0.3;}
to {opacity: 1;}
}
</style>
""", unsafe_allow_html=True)
# ------------------------------- CACHING -------------------------------
@st.cache_resource
def get_openai_model():
"""Load OpenAI GPT-3.5-Turbo model once (cached) for efficiency."""
return ChatOpenAI(model_name="gpt-4o-mini-2024-07-18", temperature=0.7)
@st.cache_resource
def get_vectorstore():
"""Load ChromaDB once (cached) for fast retrieval."""
return Chroma(
embedding_function=OpenAIEmbeddings(),
persist_directory="/home/user/chroma_db"
)
# Initialize models
llm = get_openai_model()
vectorstore = get_vectorstore()
# ------------------------------- PROMPT TEMPLATE -------------------------------
code_prompt = PromptTemplate(
input_variables=["language", "description"],
template="""
You are an **expert AI coding assistant** specializing in **ALL programming languages**, including:
- Python, JavaScript, TypeScript, PHP, C#, Java, C++, Go, Rust, Swift, Kotlin, R, SQL, Bash
- .NET, .NET Core, ASP.NET, Node.js, Django, Flask, Spring Boot, Ruby on Rails
- Web technologies: HTML, CSS, WebAssembly, WebSockets, Web3.js, GraphQL, REST APIs
**Task:** Generate a well-structured, optimized, and fully functional code snippet.
**Language:** {language}
**User Request:** {description}
- Follow industry best practices and clean code principles.
- Include relevant comments for clarity.
- If applicable, provide setup instructions.
- Ensure security and performance optimizations.
"""
)
# ------------------------------- STREAMLIT UI -------------------------------
st.title("🧠💻 Intelligent Coding Agent")
st.markdown("### Generate, Enhance, and Modify Code Seamlessly!")
languages = [
"Python", "JavaScript", "TypeScript", "PHP", "C#", "Java", "C++", "Go", "Rust", "Swift",
"Kotlin", "R", "SQL", "Bash", "HTML/CSS/JS", ".NET", ".NET Core"
]
language = st.selectbox("Select a programming language:", languages)
description = st.text_area("What do you need?", placeholder="E.g., Build an authentication system in Flask", height=150)
# ------------------------------- SESSION STATE -------------------------------
if "generated_code" not in st.session_state:
st.session_state.generated_code = ""
# ------------------------------- ANIMATED LOADER -------------------------------
def show_loader():
"""Shows an animated loading effect."""
loader_text = "⏳ Generating your code..."
for _ in range(3):
st.markdown(f"<div class='loader'>{loader_text}</div>", unsafe_allow_html=True)
time.sleep(0.6)
# ------------------------------- ASYNC FUNCTIONS -------------------------------
async def generate_code():
"""Generates optimized code while ensuring proper formatting."""
if not description.strip():
st.warning("Please enter a description!")
return
show_loader()
# Format prompt
prompt = code_prompt.format(language=language, description=description)
# Generate code asynchronously
response = await asyncio.to_thread(llm.invoke, [HumanMessage(content=prompt)])
# Store generated code in session state
st.session_state.generated_code = response.content
# Display properly formatted code block
st.subheader("Here’s your generated code:")
st.code(st.session_state.generated_code, language=language.lower())
# Save to vectorstore for reference
vectorstore.add_texts([st.session_state.generated_code])
async def enhance_code():
"""Enhances existing code with better efficiency and readability."""
if not st.session_state.generated_code:
st.warning("Generate code first before enhancing!")
return
st.info("🔄 Improving your code...")
prompt = f"Improve the following code for better efficiency and readability:\n\n{st.session_state.generated_code}"
response = await asyncio.to_thread(llm.invoke, [HumanMessage(content=prompt)])
st.session_state.generated_code = response.content
st.subheader("Here’s the improved version:")
st.code(st.session_state.generated_code, language=language.lower())
async def modify_code():
"""Modifies code based on user feedback."""
modification = st.text_area("What changes do you want?", placeholder="E.g., Add input validation")
if st.button("Apply Changes"):
if not st.session_state.generated_code:
st.warning("Generate code first before modifying!")
return
if not modification.strip():
st.warning("Please enter modification details!")
return
st.info("🔄 Making modifications...")
prompt = f"Modify the following code based on the request '{modification}':\n\n{st.session_state.generated_code}"
response = await asyncio.to_thread(llm.invoke, [HumanMessage(content=prompt)])
st.session_state.generated_code = response.content
st.subheader("Here’s the modified code:")
st.code(st.session_state.generated_code, language=language.lower())
# ------------------------------- BUTTONS -------------------------------
# ------------------------------- BUTTONS -------------------------------
col1, col2 = st.columns(2) # Ensures both buttons are of equal width
with col1:
if st.button("Generate Code", use_container_width=True):
asyncio.run(generate_code())
with col2:
if st.button("Enhance Code", use_container_width=True):
asyncio.run(enhance_code())
# ------------------------------- DOWNLOAD OPTION -------------------------------
if st.session_state.generated_code:
st.download_button("Download Code", st.session_state.generated_code, "generated_code.txt", "text/plain", use_container_width=True)
# ------------------------------- BRANDING -------------------------------
st.markdown('<p class="branding">🚀 Powered by WaysAhead Global</p>', unsafe_allow_html=True)
st.markdown("---")
st.markdown("🔹 **Optimized with OpenAI GPT-3.5, LangChain, and ChromaDB** 🔹")
|