Yaswanth123 commited on
Commit
3a7aabb
·
verified ·
1 Parent(s): 6490b57

create app.py

Browse files
Files changed (1) hide show
  1. app.py +196 -0
app.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import gradio as gr
4
+ import logging
5
+ import os
6
+ from typing import List, Dict, Any, Optional
7
+
8
+ # --- 1. CONFIGURATION FIRST ---
9
+ from config import initialize_dspy
10
+ custom_lm = initialize_dspy()
11
+
12
+ # --- 2. Now Import Other Modules ---
13
+ from config import (
14
+ API_KEY, STATE_STAGE, STATE_HISTORY, STAGE_START, STAGE_EXPLAINING,
15
+ STATE_EXPLAINER_PROMPT
16
+ )
17
+ from resource_processor import process_uploaded_files
18
+ from orchestrator import process_chat_message
19
+
20
+ # Setup basic logging
21
+ logging.basicConfig(level=logging.INFO, format='{levelname} {asctime} [%(name)s]: {message}', style='{')
22
+ logger = logging.getLogger(__name__)
23
+
24
+ def respond(
25
+ user_message: str, # The content from the textbox
26
+ chat_history_ui: List[Dict[str, str]],
27
+ app_state: Dict[str, Any],
28
+ uploaded_files: Optional[List[Any]],
29
+ explainer_prompt_display: str
30
+ ):
31
+ """
32
+ Core backend function. Receives UI state, calls orchestrator, and returns updated UI state.
33
+ This version also handles clearing the input textbox directly.
34
+ """
35
+ # Guard clause: If user sends an empty message, do nothing.
36
+ if not user_message.strip():
37
+ # Return all components unchanged, including the uncleared textbox
38
+ return chat_history_ui, app_state, gr.update(), gr.update(), gr.update(), user_message
39
+
40
+ # Guard clause: If the API key is missing, the app won't work.
41
+ if not custom_lm:
42
+ error_msg = "FATAL ERROR: AI Backend is not configured. Please check your .env file for a valid GOOGLE_API_KEY."
43
+ chat_history_ui.append({"role": "user", "content": user_message})
44
+ chat_history_ui.append({"role": "assistant", "content": error_msg})
45
+ # Keep file uploader visible on error, but clear the textbox.
46
+ yield chat_history_ui, app_state, gr.update(visible=True), gr.update(), gr.update(), ""
47
+ return
48
+
49
+ # --- Step 1: Update UI and State with User's Message ---
50
+ chat_history_ui.append({"role": "user", "content": user_message})
51
+ app_state[STATE_HISTORY].append({'role': 'user', 'parts': [{'text': user_message}]})
52
+ chat_history_ui.append({"role": "assistant", "content": ""}) # Placeholder for bot response
53
+
54
+ # First yield for immediate UI update. Hide file uploader, but don't clear textbox yet.
55
+ yield chat_history_ui, app_state, gr.update(visible=False), gr.update(), gr.update(), user_message
56
+
57
+ # --- Step 2: Handle File Uploads ---
58
+ processed_file_data = None
59
+ if app_state.get(STATE_STAGE) == STAGE_START and uploaded_files:
60
+ logger.info(f"Processing {len(uploaded_files)} files for new chat session.")
61
+ processed_file_data = process_uploaded_files(uploaded_files)
62
+
63
+ # --- Step 3: Call the Main Agent Logic (The Orchestrator) ---
64
+ try:
65
+ final_user_facing_reply, new_state = process_chat_message(
66
+ user_message_text=user_message,
67
+ current_session_state=app_state,
68
+ uploaded_resource_data=processed_file_data,
69
+ modified_explainer_prompt=explainer_prompt_display
70
+ )
71
+ app_state = new_state
72
+ except Exception as e:
73
+ logger.error(f"Critical error in orchestrator call: {e}", exc_info=True)
74
+ final_user_facing_reply = f"[SYSTEM ERROR: An exception occurred in the agent's logic. Please check the logs. Details: {e}]"
75
+
76
+ # --- Step 4: Update the UI with the AI's Final Response ---
77
+ syllabus_flag_data = app_state.get("display_syllabus_flag")
78
+ if syllabus_flag_data:
79
+ syllabus_content = syllabus_flag_data.get("content", "Error displaying syllabus.")
80
+ chat_history_ui[-1] = {"role": "assistant", "content": syllabus_content}
81
+ chat_history_ui.append({"role": "assistant", "content": final_user_facing_reply})
82
+ app_state.pop("display_syllabus_flag", None)
83
+ else:
84
+ chat_history_ui[-1]['content'] = final_user_facing_reply
85
+
86
+ # --- Step 5: Determine visibility of explainer prompt box for the final return ---
87
+ prompt_update = gr.update(visible=False)
88
+ header_update = gr.update(visible=False)
89
+ if new_state.get(STATE_STAGE) == STAGE_EXPLAINING:
90
+ prompt_value = explainer_prompt_display if explainer_prompt_display else new_state.get(STATE_EXPLAINER_PROMPT)
91
+ prompt_update = gr.update(value=prompt_value, visible=True)
92
+ header_update = gr.update(visible=True)
93
+
94
+ # Final yield: return all component states AND an empty string to clear the textbox.
95
+ yield chat_history_ui, app_state, gr.update(visible=False), header_update, prompt_update, ""
96
+
97
+ def start_new_session():
98
+ """ Resets the chat history, internal state, and all UI components for a new conversation. """
99
+ logger.info("UI action: Starting new session.")
100
+ initial_state = {
101
+ STATE_STAGE: STAGE_START,
102
+ STATE_HISTORY: [{'role': 'model', 'parts': [{'text': 'Hello! What would you like to learn about today?'}]}]
103
+ }
104
+ initial_chat_history_ui = [{"role": "assistant", "content": "Hello! What would you like to learn about today?"}]
105
+
106
+ return (
107
+ initial_chat_history_ui,
108
+ initial_state,
109
+ gr.update(value=[], visible=True), # File uploader
110
+ gr.update(visible=False), # Prompt header
111
+ gr.update(value="", visible=False), # Prompt textbox
112
+ "" # Clear the main textbox
113
+ )
114
+
115
+ # --- 3. Gradio Interface Definition ---
116
+ with gr.Blocks(theme=gr.themes.Soft(), title="Forge Guide AI Tutor") as demo:
117
+ gr.Markdown("# Forge Guide: AI Syllabus Architect")
118
+ gr.Markdown("Start a new conversation by describing what you want to learn. For new chats, you can also upload resources like PDFs or text files.")
119
+
120
+ app_state = gr.State({
121
+ STATE_STAGE: STAGE_START,
122
+ STATE_HISTORY: [{'role': 'model', 'parts': [{'text': 'Hello! What would you like to learn about today?'}]}]
123
+ })
124
+
125
+ with gr.Row():
126
+ with gr.Column(scale=4):
127
+ chatbot = gr.Chatbot(
128
+ [{"role": "assistant", "content": "Hello! What would you like to learn about today?"}],
129
+ elem_id="chatbot",
130
+ height=650,
131
+ render_markdown=True,
132
+ avatar_images=(None, "https://i.imgur.com/3pyR0Vf.png"),
133
+ type='messages',
134
+ latex_delimiters=[{"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}]
135
+ )
136
+
137
+ with gr.Row():
138
+ txt_input = gr.Textbox(
139
+ scale=4,
140
+ show_label=False,
141
+ placeholder="e.g., 'I want to build a RAG pipeline from scratch'",
142
+ container=False,
143
+ )
144
+ submit_btn = gr.Button("Send", variant="primary", scale=1, min_width=100)
145
+
146
+ with gr.Column(scale=1):
147
+ gr.Markdown("### Resources")
148
+ file_uploader = gr.File(
149
+ file_count="multiple",
150
+ label="Upload for New Chat (Optional)",
151
+ file_types=[".pdf", ".txt", ".docx"],
152
+ visible=True,
153
+ interactive=True,
154
+ )
155
+ new_session_btn = gr.Button("Start New Session", variant="secondary")
156
+ tutor_prompt_header = gr.Markdown("### Tutor Persona Prompt", visible=False)
157
+ explainer_prompt_display = gr.Textbox(
158
+ label="You can modify the tutor's persona and instructions here:",
159
+ lines=15,
160
+ interactive=True,
161
+ visible=False,
162
+ )
163
+
164
+ # --- 4. Event Listeners: Wiring the UI to the Backend ---
165
+ submit_actions = [txt_input, chatbot, app_state, file_uploader, explainer_prompt_display]
166
+ output_components = [chatbot, app_state, file_uploader, tutor_prompt_header, explainer_prompt_display, txt_input]
167
+
168
+ submit_btn.click(
169
+ fn=respond,
170
+ inputs=submit_actions,
171
+ outputs=output_components,
172
+ )
173
+
174
+ txt_input.submit(
175
+ fn=respond,
176
+ inputs=submit_actions,
177
+ outputs=output_components,
178
+ )
179
+
180
+ new_session_btn.click(
181
+ fn=start_new_session,
182
+ inputs=[],
183
+ outputs=output_components
184
+ )
185
+
186
+ # --- 5. Launch the App ---
187
+ if __name__ == "__main__":
188
+ if not API_KEY:
189
+ print("\n" + "="*60)
190
+ print("CRITICAL ERROR: Cannot launch Gradio app.")
191
+ print("Your GOOGLE_API_KEY is not set in the .env file.")
192
+ print("="*60 + "\n")
193
+ else:
194
+ print("Launching Gradio app...")
195
+ demo.queue().launch(debug=True)
196
+