WaysAheadGlobal commited on
Commit
72ef0e0
·
verified ·
1 Parent(s): 1f2290a

Update app.py

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