Spaces:
Sleeping
Sleeping
Update app1.py
Browse files
app1.py
CHANGED
|
@@ -1,214 +1,133 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
|
| 3 |
import os
|
| 4 |
import streamlit as st
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
-
from
|
| 7 |
-
from langgraph.graph import StateGraph, END
|
| 8 |
from langgraph.checkpoint.memory import MemorySaver
|
| 9 |
-
from langchain_core.messages import
|
| 10 |
-
from
|
| 11 |
-
from
|
| 12 |
-
from
|
| 13 |
-
from tools import execute_python_code
|
| 14 |
-
import io
|
| 15 |
-
import contextlib
|
| 16 |
import traceback
|
| 17 |
-
import
|
|
|
|
| 18 |
|
| 19 |
# Load environment variables
|
| 20 |
load_dotenv()
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
class State(TypedDict):
|
| 26 |
-
messages: Annotated[list, ...]
|
| 27 |
-
name: str
|
| 28 |
-
birthday: str
|
| 29 |
input: str
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
execution_result: str
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
3. Include all necessary imports and make sure the code is complete.
|
| 53 |
-
4. Include code to visualize the flow graph.
|
| 54 |
-
5. Output ONLY the final Python code.
|
| 55 |
-
|
| 56 |
-
User request:"""
|
| 57 |
-
full_prompt = system_prompt + user_prompt
|
| 58 |
-
|
| 59 |
-
for attempt in range(3):
|
| 60 |
-
try:
|
| 61 |
-
response = code_generator.invoke(full_prompt)
|
| 62 |
-
return {**state, "code": str(response)}
|
| 63 |
-
except Exception as e:
|
| 64 |
-
if "503" in str(e):
|
| 65 |
-
time.sleep(2)
|
| 66 |
-
else:
|
| 67 |
-
raise e
|
| 68 |
-
raise Exception("Code generation failed after retries.")
|
| 69 |
-
|
| 70 |
-
def execute_code(state: State):
|
| 71 |
code = state.get("code", "")
|
| 72 |
-
buffer = io.StringIO()
|
| 73 |
try:
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
| 75 |
exec(code, {})
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
except Exception:
|
| 78 |
-
|
| 79 |
-
return {
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
4. VISUALIZATION: Instructions on how to run and see the graph output.
|
| 89 |
"""
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
| 99 |
builder.add_node("Generate_Code", generate_code)
|
| 100 |
builder.add_node("Execute_Code", execute_code)
|
| 101 |
-
builder.add_node("
|
|
|
|
| 102 |
builder.set_entry_point("Generate_Code")
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
.
|
| 111 |
-
|
| 112 |
-
margin-bottom: 12px;
|
| 113 |
-
border-radius: 12px;
|
| 114 |
-
max-width: 90%;
|
| 115 |
-
}
|
| 116 |
-
.user {
|
| 117 |
-
background-color: #dcf8c6;
|
| 118 |
-
align-self: flex-end;
|
| 119 |
-
}
|
| 120 |
-
.bot {
|
| 121 |
-
background-color: #f1f0f0;
|
| 122 |
-
align-self: flex-start;
|
| 123 |
-
}
|
| 124 |
-
.input-box {
|
| 125 |
-
display: flex;
|
| 126 |
-
align-items: center;
|
| 127 |
-
gap: 0.5rem;
|
| 128 |
-
}
|
| 129 |
-
#floating-container {
|
| 130 |
-
display: flex;
|
| 131 |
-
align-items: center;
|
| 132 |
-
justify-content: space-between;
|
| 133 |
-
padding: 0.25rem 0.75rem;
|
| 134 |
-
background-color: #f9f9f9;
|
| 135 |
-
border-radius: 0.75rem;
|
| 136 |
-
margin-top: 1rem;
|
| 137 |
-
border: 1px solid #ccc;
|
| 138 |
-
}
|
| 139 |
-
.floating-popup {
|
| 140 |
-
margin-top: 0.5rem;
|
| 141 |
-
padding: 0.5rem;
|
| 142 |
-
border-radius: 0.5rem;
|
| 143 |
-
border: 1px solid #ccc;
|
| 144 |
-
background-color: white;
|
| 145 |
-
}
|
| 146 |
-
</style>
|
| 147 |
-
""", unsafe_allow_html=True)
|
| 148 |
-
|
| 149 |
-
st.title("🧠 MitraVerse")
|
| 150 |
|
| 151 |
# Initialize session state
|
| 152 |
-
|
| 153 |
-
st.session_state
|
| 154 |
-
if "
|
| 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 |
-
if st.button("⚙️ Execute Code") and st.session_state.latest_code:
|
| 192 |
-
state_input = {
|
| 193 |
-
"code": st.session_state.latest_code,
|
| 194 |
-
"input": st.session_state.latest_input
|
| 195 |
-
}
|
| 196 |
-
result = graph.invoke(state_input, node="Execute_Code")
|
| 197 |
-
st.session_state.chat_history.append(
|
| 198 |
-
AIMessage(content="**🧪 Execution Result:**\n\n" + result["execution_result"])
|
| 199 |
-
)
|
| 200 |
-
st.text("🧪 Execution Result:")
|
| 201 |
-
st.text(result["execution_result"])
|
| 202 |
-
|
| 203 |
-
if st.button("🧠 Explain Code") and st.session_state.latest_code:
|
| 204 |
-
state_input = {
|
| 205 |
-
"code": st.session_state.latest_code,
|
| 206 |
-
"input": st.session_state.latest_input
|
| 207 |
-
}
|
| 208 |
-
result = graph.invoke(state_input, node="Code_Explainer")
|
| 209 |
-
st.session_state.latest_explanation = result["explanation"]
|
| 210 |
-
st.session_state.chat_history.append(
|
| 211 |
-
AIMessage(content="**🔍 Code Explanation:**\n\n" + result["explanation"])
|
| 212 |
-
)
|
| 213 |
-
with st.expander("🔍 Code Explanation"):
|
| 214 |
-
st.markdown(result["explanation"])
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import streamlit as st
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
+
from langgraph.graph import StateGraph, END, START
|
|
|
|
| 5 |
from langgraph.checkpoint.memory import MemorySaver
|
| 6 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
| 7 |
+
from langchain_core.runnables import Runnable
|
| 8 |
+
from langchain_together import ChatTogether
|
| 9 |
+
from typing import TypedDict, List, Optional
|
|
|
|
|
|
|
|
|
|
| 10 |
import traceback
|
| 11 |
+
import io
|
| 12 |
+
import sys
|
| 13 |
|
| 14 |
# Load environment variables
|
| 15 |
load_dotenv()
|
| 16 |
+
llm = ChatTogether(model="meta-llama/Meta-Llama-3-8B-Instruct")
|
| 17 |
+
|
| 18 |
+
# Define the graph state
|
| 19 |
+
class GraphState(TypedDict):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
input: str
|
| 21 |
+
messages: List[HumanMessage | AIMessage]
|
| 22 |
+
code: Optional[str]
|
| 23 |
+
execution_result: Optional[str]
|
| 24 |
+
explanation: Optional[str]
|
| 25 |
+
|
| 26 |
+
# === Node 1: Generate Code ===
|
| 27 |
+
def generate_code(state: GraphState) -> GraphState:
|
| 28 |
+
prompt = f"""You are a senior Python developer.
|
| 29 |
+
Generate Python code for the following user request. Just return the code only, no explanation.
|
| 30 |
+
|
| 31 |
+
Request: {state['input']}
|
| 32 |
+
"""
|
| 33 |
+
messages = state["messages"] + [HumanMessage(content=prompt)]
|
| 34 |
+
response = llm.invoke(messages)
|
| 35 |
+
return {
|
| 36 |
+
**state,
|
| 37 |
+
"messages": messages + [AIMessage(content=response.content)],
|
| 38 |
+
"code": response.content
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
# === Node 2: Execute Code ===
|
| 42 |
+
def execute_code(state: GraphState) -> GraphState:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
code = state.get("code", "")
|
|
|
|
| 44 |
try:
|
| 45 |
+
buffer = io.StringIO()
|
| 46 |
+
with io.StringIO() as buf, io.StringIO() as err_buf:
|
| 47 |
+
sys.stdout = buf
|
| 48 |
+
sys.stderr = err_buf
|
| 49 |
exec(code, {})
|
| 50 |
+
output = buf.getvalue()
|
| 51 |
+
error = err_buf.getvalue()
|
| 52 |
+
sys.stdout = sys.__stdout__
|
| 53 |
+
sys.stderr = sys.__stderr__
|
| 54 |
+
result = output if output else "✅ Code executed without output."
|
| 55 |
+
if error:
|
| 56 |
+
result += "\n⚠️ Error:\n" + error
|
| 57 |
except Exception:
|
| 58 |
+
result = "❌ Exception:\n" + traceback.format_exc()
|
| 59 |
+
return {
|
| 60 |
+
**state,
|
| 61 |
+
"execution_result": result
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
# === Node 3: Explain Code ===
|
| 65 |
+
def explain_code(state: GraphState) -> GraphState:
|
| 66 |
+
prompt = f"""You are a code explainer. Please explain the following Python code:
|
| 67 |
+
{state['code']}
|
|
|
|
| 68 |
"""
|
| 69 |
+
messages = state["messages"] + [HumanMessage(content=prompt)]
|
| 70 |
+
response = llm.invoke(messages)
|
| 71 |
+
return {
|
| 72 |
+
**state,
|
| 73 |
+
"messages": messages + [AIMessage(content=response.content)],
|
| 74 |
+
"explanation": response.content
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
# === Build LangGraph ===
|
| 78 |
+
builder = StateGraph(GraphState)
|
| 79 |
builder.add_node("Generate_Code", generate_code)
|
| 80 |
builder.add_node("Execute_Code", execute_code)
|
| 81 |
+
builder.add_node("Explain_Code", explain_code)
|
| 82 |
+
|
| 83 |
builder.set_entry_point("Generate_Code")
|
| 84 |
+
builder.add_edge("Generate_Code", "Execute_Code")
|
| 85 |
+
builder.add_edge("Execute_Code", "Explain_Code")
|
| 86 |
+
builder.set_finish_point("Explain_Code")
|
| 87 |
+
|
| 88 |
+
graph = builder.compile()
|
| 89 |
+
|
| 90 |
+
# === Streamlit App ===
|
| 91 |
+
st.set_page_config(page_title="🧠 MitraVerse", page_icon="🧠")
|
| 92 |
+
st.title("🧠 MitraVerse - LangGraph Code Assistant")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
# Initialize session state
|
| 95 |
+
for key in ["chat_history", "latest_code", "latest_explanation", "execution_result"]:
|
| 96 |
+
if key not in st.session_state:
|
| 97 |
+
st.session_state[key] = [] if key == "chat_history" else ""
|
| 98 |
+
|
| 99 |
+
# User input form
|
| 100 |
+
with st.container():
|
| 101 |
+
with st.form("chat_form", clear_on_submit=True):
|
| 102 |
+
user_input = st.text_input("Ask me anything", placeholder="e.g., Write a bubble sort in Python")
|
| 103 |
+
submitted = st.form_submit_button("🚀 Run End-to-End")
|
| 104 |
+
|
| 105 |
+
if submitted and user_input:
|
| 106 |
+
st.session_state.chat_history.append(HumanMessage(content=user_input))
|
| 107 |
+
state_input = {
|
| 108 |
+
"messages": st.session_state.chat_history,
|
| 109 |
+
"input": user_input,
|
| 110 |
+
"code": "",
|
| 111 |
+
"execution_result": "",
|
| 112 |
+
"explanation": ""
|
| 113 |
+
}
|
| 114 |
+
result = graph.invoke(state_input)
|
| 115 |
+
st.session_state.latest_code = result["code"]
|
| 116 |
+
st.session_state.execution_result = result["execution_result"]
|
| 117 |
+
st.session_state.latest_explanation = result["explanation"]
|
| 118 |
+
|
| 119 |
+
# Show generated code
|
| 120 |
+
if st.session_state.latest_code:
|
| 121 |
+
st.subheader("🧾 Generated Code")
|
| 122 |
+
st.code(st.session_state.latest_code, language="python")
|
| 123 |
+
st.download_button("📥 Download Code", st.session_state.latest_code, file_name="generated_code.py")
|
| 124 |
+
|
| 125 |
+
# Show execution result
|
| 126 |
+
if st.session_state.execution_result:
|
| 127 |
+
st.subheader("🧪 Execution Result")
|
| 128 |
+
st.text(st.session_state.execution_result)
|
| 129 |
+
|
| 130 |
+
# Show code explanation
|
| 131 |
+
if st.session_state.latest_explanation:
|
| 132 |
+
st.subheader("💡 Code Explanation")
|
| 133 |
+
st.markdown(st.session_state.latest_explanation)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|