-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
216 lines (181 loc) Β· 6.55 KB
/
app.py
File metadata and controls
216 lines (181 loc) Β· 6.55 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""
Reflection Agentic Pattern - Streamlit Application
Demonstrates the Producer-Critic pattern for iterative code refinement.
"""
import streamlit as st
from agents import ReflectionPattern
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Page configuration
st.set_page_config(
page_title="Reflection Agentic Pattern",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better styling
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: bold;
color: #1E88E5;
margin-bottom: 1rem;
}
.sub-header {
font-size: 1.2rem;
color: #666;
margin-bottom: 2rem;
}
.iteration-badge {
background-color: #E3F2FD;
padding: 0.5rem 1rem;
border-radius: 5px;
font-weight: bold;
color: #1976D2;
}
.approved-badge {
background-color: #C8E6C9;
padding: 0.5rem 1rem;
border-radius: 5px;
font-weight: bold;
color: #388E3C;
}
.rejected-badge {
background-color: #FFCDD2;
padding: 0.5rem 1rem;
border-radius: 5px;
font-weight: bold;
color: #D32F2F;
}
</style>
""", unsafe_allow_html=True)
# Header
st.markdown('<div class="main-header">π Reflection Agentic Pattern</div>', unsafe_allow_html=True)
st.markdown('<div class="sub-header">Producer-Critic Pattern for Iterative Code Refinement</div>', unsafe_allow_html=True)
# Sidebar configuration
with st.sidebar:
st.header("βοΈ Settings")
# Check for API key
api_key_status = os.getenv("OPENAI_API_KEY")
if api_key_status:
st.success("β
OpenAI API Key detected")
else:
st.error("β OpenAI API Key not found")
st.info("Please set the OPENAI_API_KEY environment variable")
st.divider()
# Max iterations setting
max_iterations = st.slider(
"Max Iterations",
min_value=1,
max_value=5,
value=3,
help="Maximum number of refinement iterations"
)
st.divider()
# Pattern explanation
with st.expander("βΉοΈ About the Pattern"):
st.markdown("""
**Reflection Agentic Pattern** involves:
1. **Producer Agent**: Generates initial code based on your prompt
2. **Critic Agent**: Acts as a Senior Staff Engineer, reviewing the code
3. **Feedback Loop**: The Producer refines the code based on critique
This iterative process continues until the code is approved or max iterations are reached.
""")
# Example prompts
with st.expander("π‘ Example Prompts"):
st.markdown("""
- "Create a function to calculate Fibonacci numbers using memoization"
- "Write a class for managing a simple todo list with add, remove, and list operations"
- "Implement a binary search algorithm with proper error handling"
- "Create a decorator that logs function execution time"
""")
# Main content area
st.header("π Code Generation Request")
# User input
user_prompt = st.text_area(
"Enter your code generation request:",
height=150,
placeholder="Example: Create a function to validate email addresses using regex...",
help="Describe what Python code you want the Producer agent to generate"
)
# Generate button
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
generate_button = st.button("π Generate Code", type="primary", use_container_width=True)
# Process generation
if generate_button:
if not user_prompt.strip():
st.warning("β οΈ Please enter a code generation request")
elif not api_key_status:
st.error("β OpenAI API Key is not set. Please set the OPENAI_API_KEY environment variable.")
else:
with st.spinner("π Running Reflection Pattern..."):
try:
# Initialize and execute the pattern
reflection = ReflectionPattern(max_iterations=max_iterations)
result = reflection.execute(user_prompt)
# Store result in session state
st.session_state['result'] = result
except Exception as e:
st.error(f"β Error: {str(e)}")
st.session_state['result'] = None
# Display results if available
if 'result' in st.session_state and st.session_state['result']:
result = st.session_state['result']
st.divider()
st.header("π― Results")
# Summary metrics
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Total Iterations", result['total_iterations'])
with col2:
status = "β
Approved" if result['approved'] else "β οΈ Max Iterations Reached"
st.metric("Status", status)
with col3:
st.metric("Max Allowed", max_iterations)
st.divider()
# Thought process - show each iteration
st.header("π§ Thought Process")
for idx, iteration_data in enumerate(result['history']):
iteration_num = iteration_data['iteration']
code = iteration_data['code']
feedback = iteration_data['feedback']
approved = iteration_data['approved']
with st.expander(f"**Iteration {iteration_num}** {'β
Approved' if approved else 'π Needs Refinement'}", expanded=(idx == 0)):
# Show the generated code
st.subheader(f"π Draft {iteration_num}")
st.code(code, language="python", line_numbers=True)
st.divider()
# Show the critique
st.subheader(f"π Critique {iteration_num}")
if approved:
st.success(feedback)
else:
st.warning(feedback)
st.divider()
# Final code with syntax highlighting
st.header("β¨ Final Code")
if result['approved']:
st.success("β
Code approved by the Critic Agent!")
else:
st.info("βΉοΈ Maximum iterations reached. The code may benefit from further refinement.")
st.code(result['final_code'], language="python", line_numbers=True)
# Download button
st.download_button(
label="π₯ Download Code",
data=result['final_code'],
file_name="generated_code.py",
mime="text/plain",
use_container_width=True
)
# Footer
st.divider()
st.markdown("""
<div style="text-align: center; color: #666; padding: 2rem 0;">
<p>Built with β€οΈ using Streamlit and LangChain</p>
<p>Reflection Agentic Pattern Demo</p>
</div>
""", unsafe_allow_html=True)