Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- .gitattributes +2 -0
- Eleanor.png +3 -0
- README.md +0 -14
- Trashed.mp4 +3 -0
- buapp.py +463 -0
- bumain2.py +572 -0
- llm_logger.py +98 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
Eleanor.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
Trashed.mp4 filter=lfs diff=lfs merge=lfs -text
|
Eleanor.png
ADDED
|
Git LFS Details
|
README.md
CHANGED
|
@@ -1,14 +0,0 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: PracticeChat2
|
| 3 |
-
emoji: 💬
|
| 4 |
-
colorFrom: yellow
|
| 5 |
-
colorTo: purple
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 5.0.1
|
| 8 |
-
app_file: app.py
|
| 9 |
-
pinned: false
|
| 10 |
-
license: mit
|
| 11 |
-
short_description: Practice Chat for PFA skills
|
| 12 |
-
---
|
| 13 |
-
|
| 14 |
-
An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Trashed.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
import shutil
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import markdown
|
| 8 |
+
from markdown_pdf import MarkdownPdf, Section
|
| 9 |
+
import tempfile
|
| 10 |
+
from bumain2 import (
|
| 11 |
+
initialize_knowledge_base,
|
| 12 |
+
llm,
|
| 13 |
+
State,
|
| 14 |
+
HumanMessage,
|
| 15 |
+
SystemMessage,
|
| 16 |
+
AIMessage,
|
| 17 |
+
roleplay_agent,
|
| 18 |
+
expert_agent
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Try to import llm_logger, but make it optional for HF Spaces
|
| 22 |
+
try:
|
| 23 |
+
from llm_logger import llm_logger
|
| 24 |
+
except ImportError:
|
| 25 |
+
print("Warning: llm_logger not available - logging disabled")
|
| 26 |
+
# Create a dummy logger for HF Spaces
|
| 27 |
+
class DummyLogger:
|
| 28 |
+
def log_call(self, *args, **kwargs):
|
| 29 |
+
pass
|
| 30 |
+
llm_logger = DummyLogger()
|
| 31 |
+
|
| 32 |
+
# Initialize globals
|
| 33 |
+
knowledge_base = None
|
| 34 |
+
user_states = {} # Store user states by session ID
|
| 35 |
+
conversation_history = []
|
| 36 |
+
system_message = """
|
| 37 |
+
You are Eleanor Vance, an 82-year-old woman who has just lost her house in a landslide in Western North Carolina.
|
| 38 |
+
You are currently at a Red Cross shelter seeking help.
|
| 39 |
+
You are worried about your cat name Whiskers (a grey tabby with white paws) who is missing.
|
| 40 |
+
You are feeling overwhelmed, scared, and uncertain about the future.
|
| 41 |
+
You are having a real conversation with a counselor.
|
| 42 |
+
NEVER break character.
|
| 43 |
+
NEVER use stage directions, parentheses, emojis, etc.
|
| 44 |
+
Give ONE authentic response only and keep it mostly short.
|
| 45 |
+
"""
|
| 46 |
+
introduction_message = """
|
| 47 |
+
### Introduction
|
| 48 |
+
You are a volunteer who is helping people affected by a series of landslides in Western North Carolina.
|
| 49 |
+
You are currently doing a shift at the emergency shelter set up at the local high school gym.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def create_feedback_pdf(feedback_content):
|
| 53 |
+
"""Create a PDF from feedback content using MarkdownPDF and return the file path."""
|
| 54 |
+
if not feedback_content or feedback_content.strip() == "":
|
| 55 |
+
print("No feedback content to convert to PDF")
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
# Create a temporary file
|
| 59 |
+
temp_dir = tempfile.gettempdir()
|
| 60 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 61 |
+
pdf_path = os.path.join(temp_dir, f"expert_feedback_{timestamp}.pdf")
|
| 62 |
+
|
| 63 |
+
print(f"Creating PDF at: {pdf_path}")
|
| 64 |
+
print(f"Raw feedback content: {repr(feedback_content[:500])}...") # Debug print
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
# Create markdown content with header and render feedback as-is
|
| 68 |
+
markdown_content = f"""## Feedback Report
|
| 69 |
+
**Generated on:** {datetime.now().strftime('%B %d, %Y at %I:%M %p')}
|
| 70 |
+
---
|
| 71 |
+
|
| 72 |
+
{feedback_content}
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
print(f"Generated markdown content length: {len(markdown_content)}")
|
| 76 |
+
print(f"Markdown preview: {markdown_content[:300]}...") # Debug print
|
| 77 |
+
|
| 78 |
+
# Try to create PDF from markdown - handle potential import issues
|
| 79 |
+
try:
|
| 80 |
+
from markdown_pdf import MarkdownPdf, Section
|
| 81 |
+
pdf = MarkdownPdf()
|
| 82 |
+
pdf.add_section(Section(markdown_content, toc=False))
|
| 83 |
+
pdf.save(pdf_path)
|
| 84 |
+
print(f"PDF successfully created: {pdf_path}")
|
| 85 |
+
return pdf_path
|
| 86 |
+
except ImportError:
|
| 87 |
+
print("markdown-pdf not available, creating text file instead")
|
| 88 |
+
# Fallback: create a text file instead
|
| 89 |
+
txt_path = pdf_path.replace('.pdf', '.txt')
|
| 90 |
+
with open(txt_path, 'w', encoding='utf-8') as f:
|
| 91 |
+
f.write(markdown_content)
|
| 92 |
+
return txt_path
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Error creating PDF: {e}")
|
| 96 |
+
import traceback
|
| 97 |
+
traceback.print_exc()
|
| 98 |
+
return None
|
| 99 |
+
|
| 100 |
+
# Initialize the knowledge base during startup
|
| 101 |
+
def initialize():
|
| 102 |
+
global knowledge_base
|
| 103 |
+
print("Initializing counseling knowledge base...")
|
| 104 |
+
knowledge_base = initialize_knowledge_base()
|
| 105 |
+
return "✅ Knowledge base initialized. Ready to chat!"
|
| 106 |
+
|
| 107 |
+
def get_or_create_state(user_id="default"):
|
| 108 |
+
"""Get existing state for user or create a new one."""
|
| 109 |
+
if user_id not in user_states:
|
| 110 |
+
user_states[user_id] = State(
|
| 111 |
+
messages=[],
|
| 112 |
+
roleplay_messages=[
|
| 113 |
+
SystemMessage(content=system_message)
|
| 114 |
+
],
|
| 115 |
+
message_type="roleplay",
|
| 116 |
+
next="roleplay",
|
| 117 |
+
session_mode="roleplay",
|
| 118 |
+
total_input_tokens=0,
|
| 119 |
+
total_output_tokens=0
|
| 120 |
+
)
|
| 121 |
+
return user_states[user_id]
|
| 122 |
+
|
| 123 |
+
def send_message(message, history, session_mode, feedback_history, user_id="default"):
|
| 124 |
+
"""Process a message in the current mode."""
|
| 125 |
+
state = get_or_create_state(user_id)
|
| 126 |
+
|
| 127 |
+
# Log the user message
|
| 128 |
+
llm_logger.log_call(
|
| 129 |
+
messages=[{"role": "user", "content": message}],
|
| 130 |
+
model=llm.model_name if hasattr(llm, 'model_name') else "unknown",
|
| 131 |
+
session_mode=session_mode,
|
| 132 |
+
context="User input message"
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# Check for reset command
|
| 136 |
+
if message.lower() in ["reset", "restart", "new session"]:
|
| 137 |
+
# Reset the state
|
| 138 |
+
if user_id in user_states:
|
| 139 |
+
del user_states[user_id]
|
| 140 |
+
state = get_or_create_state(user_id)
|
| 141 |
+
return "Session reset. Starting a new conversation.", session_mode, "Feedback cleared.", False
|
| 142 |
+
|
| 143 |
+
# Process according to current mode
|
| 144 |
+
if session_mode == "expert":
|
| 145 |
+
response = process_expert_mode(message, state)
|
| 146 |
+
# Expert feedback goes to the feedback box, not main chat
|
| 147 |
+
new_feedback = f"**Your Question:** {message}\n\n**Expert Feedback:** {response}\n\n---\n\n"
|
| 148 |
+
updated_feedback = new_feedback + feedback_history
|
| 149 |
+
|
| 150 |
+
# Convert markdown to HTML for scrollable display
|
| 151 |
+
updated_feedback_html = markdown.markdown(updated_feedback)
|
| 152 |
+
|
| 153 |
+
print(f"Updated feedback length: {len(updated_feedback)}") # Debug print
|
| 154 |
+
print(f"New feedback preview: {new_feedback[:200]}...") # Debug print
|
| 155 |
+
return "", session_mode, updated_feedback_html, True # Open accordion when expert feedback is added
|
| 156 |
+
else:
|
| 157 |
+
response = process_roleplay_mode(message, state)
|
| 158 |
+
return response, session_mode, feedback_history, False # Keep accordion state unchanged
|
| 159 |
+
|
| 160 |
+
def process_roleplay_mode(message, state):
|
| 161 |
+
"""Process a message in roleplay mode."""
|
| 162 |
+
|
| 163 |
+
# Log system prompt if it exists in the roleplay_messages
|
| 164 |
+
if state.get("roleplay_messages") and any(isinstance(msg, SystemMessage) for msg in state.get("roleplay_messages", [])):
|
| 165 |
+
system_msgs = [msg.content for msg in state.get("roleplay_messages", []) if isinstance(msg, SystemMessage)]
|
| 166 |
+
if system_msgs:
|
| 167 |
+
llm_logger.log_call(
|
| 168 |
+
messages=[{"role": "system", "content": system_msgs[0]}],
|
| 169 |
+
model=llm.model_name if hasattr(llm, 'model_name') else "unknown",
|
| 170 |
+
context="Roleplay system prompt"
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# Add user message to state
|
| 174 |
+
state["messages"] = [HumanMessage(content=message)]
|
| 175 |
+
|
| 176 |
+
# Get response using the roleplay agent
|
| 177 |
+
result = roleplay_agent(state)
|
| 178 |
+
|
| 179 |
+
# Update state with result
|
| 180 |
+
state.update(result)
|
| 181 |
+
|
| 182 |
+
# Return the AI response
|
| 183 |
+
if state["messages"] and len(state["messages"]) > 0:
|
| 184 |
+
response = state["messages"][-1].content
|
| 185 |
+
return response
|
| 186 |
+
|
| 187 |
+
def process_expert_mode(message, state):
|
| 188 |
+
"""Process a message in expert mode."""
|
| 189 |
+
# Add user message to state
|
| 190 |
+
state["messages"] = [HumanMessage(content=message)]
|
| 191 |
+
|
| 192 |
+
# Get response using the expert agent
|
| 193 |
+
result = expert_agent(state)
|
| 194 |
+
|
| 195 |
+
# Update state with result
|
| 196 |
+
state.update(result)
|
| 197 |
+
|
| 198 |
+
# If switching to roleplay mode, handle the transition
|
| 199 |
+
if state.get("switching_to_roleplay"):
|
| 200 |
+
state.pop("switching_to_roleplay", None)
|
| 201 |
+
# We'll handle the mode change in the calling function
|
| 202 |
+
return "Switching back to roleplay mode. Continue your conversation with the client."
|
| 203 |
+
|
| 204 |
+
# Return the expert response
|
| 205 |
+
if state["messages"] and len(state["messages"]) > 0:
|
| 206 |
+
response = state["messages"][-1].content
|
| 207 |
+
return response
|
| 208 |
+
|
| 209 |
+
def exit_application():
|
| 210 |
+
"""Function to handle application exit"""
|
| 211 |
+
# Gracefully shut down the application
|
| 212 |
+
os._exit(0) # Force exit as sys.exit() might not work in Gradio's threaded environment
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def build_interface():
|
| 216 |
+
"""Build the Gradio interface."""
|
| 217 |
+
|
| 218 |
+
with gr.Blocks(title="Psychological First Aid Skills Practice", css="""
|
| 219 |
+
#feedback-content {
|
| 220 |
+
max-height: 400px;
|
| 221 |
+
overflow-y: auto;
|
| 222 |
+
padding: 10px;
|
| 223 |
+
border: 1px solid #444;
|
| 224 |
+
border-radius: 5px;
|
| 225 |
+
background-color: #000000;
|
| 226 |
+
color: #ffffff;
|
| 227 |
+
line-height: 1.6;
|
| 228 |
+
}
|
| 229 |
+
#feedback-content h1, #feedback-content h2, #feedback-content h3 {
|
| 230 |
+
color: #ffffff !important;
|
| 231 |
+
}
|
| 232 |
+
#feedback-content strong {
|
| 233 |
+
color: #ffffff !important;
|
| 234 |
+
}
|
| 235 |
+
#feedback-content p {
|
| 236 |
+
margin-bottom: 10px;
|
| 237 |
+
color: #ffffff !important;
|
| 238 |
+
}
|
| 239 |
+
#feedback-content * {
|
| 240 |
+
color: #ffffff !important;
|
| 241 |
+
}
|
| 242 |
+
""") as interface:
|
| 243 |
+
with gr.Row():
|
| 244 |
+
gr.Markdown("# Psychological First Aid Skills Practice")
|
| 245 |
+
gr.Markdown("Give me some feedback and ideas for this application at this link: [Feedback Form](https://docs.google.com/forms/d/e/1FAIpQLSdJ_gEHrOq4V08bUgcRpXUq3i-Tgs3n_Gmoy1CB-1fB-7yHuw/viewform?usp=header)")
|
| 246 |
+
|
| 247 |
+
# State management
|
| 248 |
+
session_mode = gr.State(value="roleplay") # Start in roleplay mode
|
| 249 |
+
|
| 250 |
+
with gr.Row():
|
| 251 |
+
with gr.Column(scale=3):
|
| 252 |
+
chatbot = gr.Chatbot(height=500, type='messages')
|
| 253 |
+
|
| 254 |
+
with gr.Row():
|
| 255 |
+
msg = gr.Textbox(
|
| 256 |
+
placeholder="Type your message here...",
|
| 257 |
+
container=False,
|
| 258 |
+
scale=7,
|
| 259 |
+
)
|
| 260 |
+
submit = gr.Button("Send", variant="primary", scale=1)
|
| 261 |
+
|
| 262 |
+
with gr.Row():
|
| 263 |
+
reset_btn = gr.Button("Reset Session")
|
| 264 |
+
|
| 265 |
+
with gr.Column(scale=2):
|
| 266 |
+
with gr.Accordion("How to use this Application", open=False):
|
| 267 |
+
gr.Markdown("""
|
| 268 |
+
- **Client Mode**: Talk directly with your client.
|
| 269 |
+
- **Expert Coach Mode**: Get feedback on your counseling approach.
|
| 270 |
+
- Say something like "give me feedback" for a comprehensive summary
|
| 271 |
+
or ask a specific question (i.e "Help me with what to ask next")
|
| 272 |
+
- Use the **Expert Feedback Box** to see feedback from the expert coach.
|
| 273 |
+
- Choose **Client Mode** to return to the client conversation.
|
| 274 |
+
- Click **Reset Session** to start a new conversation.
|
| 275 |
+
- Please give me feedback and ideas for this application at this link:
|
| 276 |
+
[Feedback Form](https://docs.google.com/forms/d/e/1FAIpQLSdJ_gEHrOq4V08bUgcRpXUq3i-Tgs3n_Gmoy1CB-1fB-7yHuw/viewform?usp=header)
|
| 277 |
+
""") # Add Eleanor's image here
|
| 278 |
+
with gr.Accordion("Meet Eleanor", open=False):
|
| 279 |
+
with gr.Row():
|
| 280 |
+
with gr.Column(scale=1):
|
| 281 |
+
with gr.Row():
|
| 282 |
+
# Only show image/video if files exist
|
| 283 |
+
if os.path.exists("Eleanor.png"):
|
| 284 |
+
gr.Image("Eleanor.png", label="Eleanor Vance", height=150, show_label=False, show_download_button=False)
|
| 285 |
+
if os.path.exists("Trashed.mp4"):
|
| 286 |
+
gr.Video("Trashed.mp4", label="Eleanor Vance Video", height=150, show_label=False, show_download_button=False)
|
| 287 |
+
with gr.Column(scale=3):
|
| 288 |
+
gr.Markdown("""
|
| 289 |
+
**Eleanor Vance** is an 82-year-old widow who has just lost her home in a landslide.
|
| 290 |
+
She is currently at a Red Cross shelter seeking help.
|
| 291 |
+
""")
|
| 292 |
+
|
| 293 |
+
# Add a single toggle button for mode switching
|
| 294 |
+
mode_toggle = gr.Radio(
|
| 295 |
+
choices=["Client Mode", "Expert Coach Mode"],
|
| 296 |
+
value="Client Mode",
|
| 297 |
+
label="Interaction Mode",
|
| 298 |
+
info="Switch between talking to the client or getting expert feedback"
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
# Expert Feedback Box - make it a variable so we can control it
|
| 302 |
+
feedback_accordion = gr.Accordion("See feedback here...", open=False)
|
| 303 |
+
with feedback_accordion:
|
| 304 |
+
feedback_box = gr.HTML(
|
| 305 |
+
value="",
|
| 306 |
+
elem_id="feedback-content"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
# Feedback action buttons
|
| 310 |
+
with gr.Row():
|
| 311 |
+
clear_feedback_btn = gr.Button("Clear Feedback", variant="secondary", scale=1)
|
| 312 |
+
download_feedback_btn = gr.Button("Create PDF", variant="primary", scale=1)
|
| 313 |
+
|
| 314 |
+
# File component for PDF download - now visible and positioned below buttons
|
| 315 |
+
feedback_file = gr.File(
|
| 316 |
+
label="Download Feedback PDF",
|
| 317 |
+
visible=False,
|
| 318 |
+
interactive=False
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
# Display a welcome message at startup
|
| 322 |
+
def show_welcome_msg(history):
|
| 323 |
+
|
| 324 |
+
return history + [{"role": "assistant", "content": introduction_message}]
|
| 325 |
+
|
| 326 |
+
# Show welcome message on page load
|
| 327 |
+
interface.load(show_welcome_msg, [chatbot], [chatbot])
|
| 328 |
+
|
| 329 |
+
# Handle message submission
|
| 330 |
+
def submit_message(message, history, current_mode, feedback_history):
|
| 331 |
+
if message.strip() == "":
|
| 332 |
+
return "", history, current_mode, feedback_history, gr.update()
|
| 333 |
+
|
| 334 |
+
response, new_mode, updated_feedback, should_open_accordion = send_message(message, history, current_mode, feedback_history)
|
| 335 |
+
|
| 336 |
+
# Only add to chat history if in roleplay mode
|
| 337 |
+
if current_mode == "roleplay" and response:
|
| 338 |
+
history.append({"role": "user", "content": message})
|
| 339 |
+
history.append({"role": "assistant", "content": response})
|
| 340 |
+
|
| 341 |
+
# Only update accordion if we're in expert mode and should open it
|
| 342 |
+
if current_mode == "expert" and should_open_accordion:
|
| 343 |
+
accordion_update = gr.update(open=True)
|
| 344 |
+
else:
|
| 345 |
+
accordion_update = gr.update() # Keep current state unchanged
|
| 346 |
+
|
| 347 |
+
return "", history, new_mode, updated_feedback, accordion_update
|
| 348 |
+
|
| 349 |
+
msg.submit(
|
| 350 |
+
submit_message,
|
| 351 |
+
[msg, chatbot, session_mode, feedback_box],
|
| 352 |
+
[msg, chatbot, session_mode, feedback_box, feedback_accordion]
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
submit.click(
|
| 356 |
+
submit_message,
|
| 357 |
+
[msg, chatbot, session_mode, feedback_box],
|
| 358 |
+
[msg, chatbot, session_mode, feedback_box, feedback_accordion]
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
# Mode toggle handling
|
| 363 |
+
def handle_mode_toggle(mode_value, history):
|
| 364 |
+
new_mode = "roleplay" if mode_value == "Client Mode" else "expert"
|
| 365 |
+
|
| 366 |
+
# Add a system message to indicate mode change
|
| 367 |
+
if new_mode == "roleplay":
|
| 368 |
+
history.append({"role": "system", "content": "Switching to client mode. You're now talking directly with Margaret."})
|
| 369 |
+
else:
|
| 370 |
+
history.append({"role": "system", "content": "Switching to expert coach mode. Ask for feedback - responses will appear in the Expert Feedback box."})
|
| 371 |
+
|
| 372 |
+
return history, new_mode
|
| 373 |
+
|
| 374 |
+
mode_toggle.change(
|
| 375 |
+
handle_mode_toggle,
|
| 376 |
+
[mode_toggle, chatbot],
|
| 377 |
+
[chatbot, session_mode]
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
# Reset button
|
| 381 |
+
def reset_chat():
|
| 382 |
+
# Clear the user state
|
| 383 |
+
if "default" in user_states:
|
| 384 |
+
del user_states["default"]
|
| 385 |
+
get_or_create_state("default") # Recreate state
|
| 386 |
+
|
| 387 |
+
# Return to roleplay mode by default
|
| 388 |
+
new_history = [{"role": "assistant", "content": introduction_message}]
|
| 389 |
+
|
| 390 |
+
return new_history, "", "roleplay", "Client Mode", "", gr.update(open=False)
|
| 391 |
+
|
| 392 |
+
reset_btn.click(
|
| 393 |
+
reset_chat,
|
| 394 |
+
None,
|
| 395 |
+
[chatbot, msg, session_mode, mode_toggle, feedback_box, feedback_accordion]
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
# Clear feedback button
|
| 399 |
+
def clear_feedback():
|
| 400 |
+
return ""
|
| 401 |
+
|
| 402 |
+
clear_feedback_btn.click(
|
| 403 |
+
clear_feedback,
|
| 404 |
+
None,
|
| 405 |
+
[feedback_box]
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
# Download feedback as PDF - Updated to show file component and populate it
|
| 409 |
+
def download_feedback(feedback_content):
|
| 410 |
+
print(f"Download button clicked. Feedback content length: {len(feedback_content) if feedback_content else 0}")
|
| 411 |
+
|
| 412 |
+
if not feedback_content or feedback_content.strip() == "":
|
| 413 |
+
print("No feedback content available")
|
| 414 |
+
return gr.update(visible=False), None # Keep hidden, no file
|
| 415 |
+
|
| 416 |
+
try:
|
| 417 |
+
pdf_path = create_feedback_pdf(feedback_content)
|
| 418 |
+
print(f"PDF created at: {pdf_path}")
|
| 419 |
+
|
| 420 |
+
if pdf_path and os.path.exists(pdf_path):
|
| 421 |
+
print(f"PDF file exists and is ready for download: {pdf_path}")
|
| 422 |
+
return gr.update(visible=True), pdf_path # Show component and provide file
|
| 423 |
+
else:
|
| 424 |
+
print("PDF file was not created successfully")
|
| 425 |
+
return gr.update(visible=False), None # Keep hidden, no file
|
| 426 |
+
except Exception as e:
|
| 427 |
+
print(f"Error in download_feedback: {e}")
|
| 428 |
+
return gr.update(visible=False), None # Keep hidden, no file
|
| 429 |
+
|
| 430 |
+
download_feedback_btn.click(
|
| 431 |
+
fn=download_feedback,
|
| 432 |
+
inputs=[feedback_box],
|
| 433 |
+
outputs=[feedback_file, feedback_file] # Update both visibility and content
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
return interface
|
| 437 |
+
|
| 438 |
+
# Add a function to recreate embeddings if needed
|
| 439 |
+
def recreate_embeddings(pdf_directory="./counseling_materials/", persist_directory="./chroma_db"):
|
| 440 |
+
"""Force recreation of embeddings from PDF documents."""
|
| 441 |
+
global knowledge_base
|
| 442 |
+
|
| 443 |
+
# Remove existing database if it exists
|
| 444 |
+
if os.path.exists(persist_directory):
|
| 445 |
+
print(f"Removing existing database at {persist_directory}")
|
| 446 |
+
try:
|
| 447 |
+
shutil.rmtree(persist_directory)
|
| 448 |
+
print(f"Removed existing database directory: {persist_directory}")
|
| 449 |
+
except Exception as e:
|
| 450 |
+
print(f"Error removing directory {persist_directory}: {e}")
|
| 451 |
+
|
| 452 |
+
# Initialize the knowledge base which will create new embeddings
|
| 453 |
+
knowledge_base = initialize_knowledge_base(force_reload=True)
|
| 454 |
+
|
| 455 |
+
return "✅ Embeddings recreated from documents."
|
| 456 |
+
|
| 457 |
+
if __name__ == "__main__":
|
| 458 |
+
# Initialize knowledge base
|
| 459 |
+
initialize()
|
| 460 |
+
|
| 461 |
+
# Create and launch the interface
|
| 462 |
+
interface = build_interface()
|
| 463 |
+
interface.launch(share=True)
|
bumain2.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dotenv import load_dotenv
|
| 2 |
+
from typing import Union, Literal, Annotated, Sequence, TypedDict # Type hinting utilities
|
| 3 |
+
from langgraph.graph import StateGraph, START, END # Graph structure and node types
|
| 4 |
+
from langgraph.graph.message import add_messages # Message handling utility reducer function
|
| 5 |
+
from langchain_openai import ChatOpenAI # OpenAI-compatible chat model wrapper
|
| 6 |
+
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage # Message types
|
| 7 |
+
from langchain_core.messages import ToolMessage
|
| 8 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 9 |
+
from langchain_chroma import Chroma # Correct import for Chroma
|
| 10 |
+
import ollama # Ollama integration for local model execution
|
| 11 |
+
from langchain_ollama import OllamaEmbeddings # Correct import for OllamaEmbeddings
|
| 12 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 13 |
+
from langchain_core.documents import Document # Use correct import for Document
|
| 14 |
+
import glob
|
| 15 |
+
from langgraph.prebuilt import ToolNode # Prebuilt nodes for tool integration
|
| 16 |
+
from pydantic import BaseModel, Field
|
| 17 |
+
import os # Operating system interface for environment variables
|
| 18 |
+
import sys # For error handling and debugging
|
| 19 |
+
import shutil # For directory manipulation
|
| 20 |
+
import argparse # For command-line argument parsing
|
| 21 |
+
|
| 22 |
+
# # Load environment variables from .env file, override existing ones
|
| 23 |
+
load_dotenv(override=True)
|
| 24 |
+
|
| 25 |
+
# Error handling for initialization
|
| 26 |
+
try:
|
| 27 |
+
# Initialize the Large Language Model (LLM) with OpenRouter configuration
|
| 28 |
+
llm = ChatOpenAI(
|
| 29 |
+
# model="deepseek/deepseek-r1-distill-qwen-32b:free", # Free model for testing
|
| 30 |
+
model = "google/gemini-2.0-flash-001", # very cheap model and low latency
|
| 31 |
+
api_key=os.getenv("OPENROUTER_KEY"), # Authentication key for API access
|
| 32 |
+
base_url="https://openrouter.ai/api/v1", # Custom endpoint for OpenRouter service
|
| 33 |
+
temperature=0.7, # Controls randomness in responses (0.0 = deterministic, 1.0 = very random)
|
| 34 |
+
max_tokens=10000 # Maximum number of tokens in the response
|
| 35 |
+
)
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"Error initializing LLM: {e}")
|
| 38 |
+
sys.exit(1)
|
| 39 |
+
|
| 40 |
+
# Define the state structure for the conversation graph
|
| 41 |
+
class State(TypedDict):
|
| 42 |
+
"""State structure for the conversation graph."""
|
| 43 |
+
messages: list[Union[HumanMessage, SystemMessage, AIMessage]]
|
| 44 |
+
roleplay_messages: list[Union[HumanMessage, SystemMessage, AIMessage]] # Separate roleplay history
|
| 45 |
+
message_type: str # Add message type for routing
|
| 46 |
+
next: str # Add next field for routing
|
| 47 |
+
session_mode: str # Track current session mode
|
| 48 |
+
total_input_tokens: int # Track total input tokens used
|
| 49 |
+
total_output_tokens: int # Track total output tokens used
|
| 50 |
+
|
| 51 |
+
class CounselingKnowledgeBase:
|
| 52 |
+
def __init__(self, pdf_directory="./counseling_materials/", persist_directory="./chroma_db", force_reload=False):
|
| 53 |
+
"""Initialize the knowledge base with PDF materials."""
|
| 54 |
+
self.pdf_directory = pdf_directory
|
| 55 |
+
self.persist_directory = persist_directory
|
| 56 |
+
self.vectorstore = None
|
| 57 |
+
self.force_reload = force_reload
|
| 58 |
+
self.full_documents = [] # Store full document text
|
| 59 |
+
|
| 60 |
+
# Error handling for embedding model initialization
|
| 61 |
+
try:
|
| 62 |
+
self.embeddings = OllamaEmbeddings(
|
| 63 |
+
model="mxbai-embed-large"
|
| 64 |
+
)
|
| 65 |
+
self.load_documents()
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"Error initializing embeddings model: {e}")
|
| 68 |
+
print("Make sure Ollama is running and mxbai-embed-large model is available")
|
| 69 |
+
self.embeddings = None
|
| 70 |
+
|
| 71 |
+
def load_documents(self):
|
| 72 |
+
"""Load and process PDF documents into a vector store."""
|
| 73 |
+
if self.embeddings is None:
|
| 74 |
+
print("Cannot load documents: embedding model not initialized")
|
| 75 |
+
return
|
| 76 |
+
|
| 77 |
+
# If force reload is enabled, delete the existing database
|
| 78 |
+
if self.force_reload and os.path.exists(self.persist_directory):
|
| 79 |
+
print(f"Forcing reload of embeddings. Removing existing database at {self.persist_directory}")
|
| 80 |
+
try:
|
| 81 |
+
shutil.rmtree(self.persist_directory)
|
| 82 |
+
print(f"Removed existing database directory: {self.persist_directory}")
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(f"Error removing directory {self.persist_directory}: {e}")
|
| 85 |
+
|
| 86 |
+
# Check if vectorstore already exists
|
| 87 |
+
if not self.force_reload and os.path.exists(self.persist_directory) and os.listdir(self.persist_directory):
|
| 88 |
+
print(f"Loading existing knowledge base from {self.persist_directory}")
|
| 89 |
+
try:
|
| 90 |
+
self.vectorstore = Chroma(
|
| 91 |
+
persist_directory=self.persist_directory,
|
| 92 |
+
embedding_function=self.embeddings
|
| 93 |
+
)
|
| 94 |
+
# We still need to load the full documents
|
| 95 |
+
self.load_full_documents()
|
| 96 |
+
print("Successfully loaded existing knowledge base")
|
| 97 |
+
return
|
| 98 |
+
except Exception as e:
|
| 99 |
+
print(f"Error loading existing knowledge base: {e}")
|
| 100 |
+
print("Creating new knowledge base...")
|
| 101 |
+
|
| 102 |
+
# Load full documents regardless of whether we're using the vectorstore
|
| 103 |
+
self.load_full_documents()
|
| 104 |
+
|
| 105 |
+
# The rest of the method for creating the vectorstore (still useful for future functionality)
|
| 106 |
+
documents = []
|
| 107 |
+
|
| 108 |
+
# Find all PDF files in the directory
|
| 109 |
+
pdf_files = glob.glob(f"{self.pdf_directory}*.pdf")
|
| 110 |
+
|
| 111 |
+
if not pdf_files:
|
| 112 |
+
print(f"Warning: No PDF files found in {self.pdf_directory}")
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
# Load each PDF
|
| 116 |
+
for pdf_file in pdf_files:
|
| 117 |
+
try:
|
| 118 |
+
loader = PyPDFLoader(pdf_file)
|
| 119 |
+
docs = loader.load()
|
| 120 |
+
|
| 121 |
+
# Add source metadata
|
| 122 |
+
for doc in docs:
|
| 123 |
+
doc.metadata['source'] = pdf_file
|
| 124 |
+
|
| 125 |
+
documents.extend(docs)
|
| 126 |
+
print(f"Loaded: {pdf_file}")
|
| 127 |
+
except Exception as e:
|
| 128 |
+
print(f"Error loading {pdf_file}: {e}")
|
| 129 |
+
|
| 130 |
+
if documents:
|
| 131 |
+
# Split documents into chunks
|
| 132 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 133 |
+
chunk_size=1000,
|
| 134 |
+
chunk_overlap=200
|
| 135 |
+
)
|
| 136 |
+
splits = text_splitter.split_documents(documents)
|
| 137 |
+
|
| 138 |
+
# Create vector store
|
| 139 |
+
print("Creating embeddings... This may take a few minutes.")
|
| 140 |
+
try:
|
| 141 |
+
self.vectorstore = Chroma.from_documents(
|
| 142 |
+
documents=splits,
|
| 143 |
+
embedding=self.embeddings,
|
| 144 |
+
persist_directory=self.persist_directory
|
| 145 |
+
)
|
| 146 |
+
print(f"Created knowledge base with {len(splits)} document chunks")
|
| 147 |
+
except Exception as e:
|
| 148 |
+
print(f"Error creating vector store: {e}")
|
| 149 |
+
else:
|
| 150 |
+
print("No documents were successfully loaded")
|
| 151 |
+
|
| 152 |
+
def load_full_documents(self):
|
| 153 |
+
"""Load the full text of all PDF documents."""
|
| 154 |
+
self.full_documents = []
|
| 155 |
+
|
| 156 |
+
# Find all PDF files in the directory
|
| 157 |
+
pdf_files = glob.glob(f"{self.pdf_directory}*.pdf")
|
| 158 |
+
|
| 159 |
+
if not pdf_files:
|
| 160 |
+
print(f"Warning: No PDF files found in {self.pdf_directory}")
|
| 161 |
+
return
|
| 162 |
+
|
| 163 |
+
# Load each PDF
|
| 164 |
+
for pdf_file in pdf_files:
|
| 165 |
+
try:
|
| 166 |
+
loader = PyPDFLoader(pdf_file)
|
| 167 |
+
docs = loader.load()
|
| 168 |
+
|
| 169 |
+
# Extract file name without path and extension
|
| 170 |
+
file_name = os.path.basename(pdf_file)
|
| 171 |
+
file_name = os.path.splitext(file_name)[0]
|
| 172 |
+
|
| 173 |
+
# Combine all pages into a single document
|
| 174 |
+
full_text = "\n\n".join([doc.page_content for doc in docs])
|
| 175 |
+
|
| 176 |
+
# Add to our full documents collection
|
| 177 |
+
self.full_documents.append({
|
| 178 |
+
"title": file_name,
|
| 179 |
+
"content": full_text[:50000] # Limit content size to avoid context overflow
|
| 180 |
+
})
|
| 181 |
+
|
| 182 |
+
print(f"Loaded full text: {file_name}")
|
| 183 |
+
except Exception as e:
|
| 184 |
+
print(f"Error loading full text of {pdf_file}: {e}")
|
| 185 |
+
|
| 186 |
+
def search_relevant_content(self, query, k=3):
|
| 187 |
+
"""Search for relevant counseling content."""
|
| 188 |
+
if not self.vectorstore:
|
| 189 |
+
return []
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
docs = self.vectorstore.similarity_search(query, k=k)
|
| 193 |
+
return docs
|
| 194 |
+
except Exception as e:
|
| 195 |
+
print(f"Error searching knowledge base: {e}")
|
| 196 |
+
return []
|
| 197 |
+
|
| 198 |
+
def get_all_documents(self):
|
| 199 |
+
"""Return all stored document contents."""
|
| 200 |
+
return self.full_documents
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# Initialize knowledge base globally
|
| 204 |
+
knowledge_base = None
|
| 205 |
+
|
| 206 |
+
def initialize_knowledge_base(force_reload=False):
|
| 207 |
+
"""Initialize the counseling knowledge base."""
|
| 208 |
+
global knowledge_base
|
| 209 |
+
try:
|
| 210 |
+
knowledge_base = CounselingKnowledgeBase(force_reload=force_reload)
|
| 211 |
+
return knowledge_base
|
| 212 |
+
except Exception as e:
|
| 213 |
+
print(f"Warning: Could not initialize knowledge base: {e}")
|
| 214 |
+
return None
|
| 215 |
+
|
| 216 |
+
# Define a Pydantic model for classifying messages
|
| 217 |
+
class MessageClassifier(BaseModel):
|
| 218 |
+
message_type: Literal["roleplay", "expert"] = Field(
|
| 219 |
+
default="roleplay",
|
| 220 |
+
description="Classify if the message is asking for feedback or not."
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
# Define the function to classify messages based on their content
|
| 224 |
+
def classify_message(state: State):
|
| 225 |
+
# Get the last message in the conversation
|
| 226 |
+
last_message = state["messages"][-1]
|
| 227 |
+
|
| 228 |
+
# Use a simple keyword-based classification
|
| 229 |
+
message_content = last_message.content.lower()
|
| 230 |
+
|
| 231 |
+
# Check for keywords that indicate expert/feedback requests
|
| 232 |
+
expert_keywords = ['feedback', 'review', 'expert', 'advice', 'help me improve', 'how did i do']
|
| 233 |
+
return_keywords = ['continue', 'back to roleplay', 'return', 'keep going']
|
| 234 |
+
|
| 235 |
+
# If currently in expert mode, only return to roleplay if explicitly requested
|
| 236 |
+
if state.get("session_mode") == "expert":
|
| 237 |
+
if any(keyword in message_content for keyword in return_keywords):
|
| 238 |
+
return {"message_type": "roleplay"}
|
| 239 |
+
else:
|
| 240 |
+
return {"message_type": "expert"} # Stay in expert mode
|
| 241 |
+
|
| 242 |
+
# If in roleplay mode, check for expert requests
|
| 243 |
+
if any(keyword in message_content for keyword in expert_keywords):
|
| 244 |
+
return {"message_type": "expert"}
|
| 245 |
+
else:
|
| 246 |
+
return {"message_type": "roleplay"}
|
| 247 |
+
|
| 248 |
+
def clear_screen():
|
| 249 |
+
"""Clear the terminal screen."""
|
| 250 |
+
if os.name == 'nt': # Windows
|
| 251 |
+
os.system('cls')
|
| 252 |
+
else: # macOS and Linux
|
| 253 |
+
os.system('clear')
|
| 254 |
+
|
| 255 |
+
def display_roleplay_history(state: State):
|
| 256 |
+
"""Display the roleplay conversation history without system messages."""
|
| 257 |
+
if "roleplay_messages" not in state or not state["roleplay_messages"]:
|
| 258 |
+
return
|
| 259 |
+
|
| 260 |
+
print("=== Conversation History ===\n")
|
| 261 |
+
|
| 262 |
+
for msg in state["roleplay_messages"]:
|
| 263 |
+
if isinstance(msg, SystemMessage):
|
| 264 |
+
continue # Skip system messages
|
| 265 |
+
elif isinstance(msg, HumanMessage):
|
| 266 |
+
print(f"You: {msg.content}")
|
| 267 |
+
elif isinstance(msg, AIMessage):
|
| 268 |
+
print(f"Client: {msg.content}")
|
| 269 |
+
|
| 270 |
+
print("\n" + "="*50)
|
| 271 |
+
print("Continuing roleplay...\n")
|
| 272 |
+
|
| 273 |
+
# Define the routing function to direct the conversation flow based on message type
|
| 274 |
+
def router(state: State):
|
| 275 |
+
message_type = state["message_type"]
|
| 276 |
+
if message_type == "expert":
|
| 277 |
+
return {"next": "expert"}
|
| 278 |
+
else:
|
| 279 |
+
return {"next": "roleplay"}
|
| 280 |
+
|
| 281 |
+
# create the agent functions with different system messages
|
| 282 |
+
|
| 283 |
+
def roleplay_agent(state: State):
|
| 284 |
+
# Initialize roleplay_messages if not present
|
| 285 |
+
if "roleplay_messages" not in state:
|
| 286 |
+
state["roleplay_messages"] = []
|
| 287 |
+
|
| 288 |
+
# Add system message only if roleplay_messages is empty
|
| 289 |
+
if not state["roleplay_messages"]:
|
| 290 |
+
state["roleplay_messages"] = [
|
| 291 |
+
SystemMessage(content="""
|
| 292 |
+
You are Margaret, an 82-year-old woman who has just lost her house in a landslide.
|
| 293 |
+
You are currently at a Red Cross shelter seeking help.
|
| 294 |
+
You are worried about your cat name Whiskers (a grey tabby with white paws) who is missing.
|
| 295 |
+
You are feeling overwhelmed, scared, and uncertain about the future.
|
| 296 |
+
You are having a real conversation with a counselor.
|
| 297 |
+
CRITICAL INSTRUCTIONS:
|
| 298 |
+
- You must respond with ONLY ONE response as Margaret
|
| 299 |
+
- NEVER provide multiple options or numbered lists
|
| 300 |
+
- NEVER generate examples or alternatives
|
| 301 |
+
- You are having a real conversation, not creating training data
|
| 302 |
+
- Respond naturally as if you are actually Margaret talking to the counselor
|
| 303 |
+
- NEVER use descriptive cues, stage directions, or actions in asterisks like *chokes up*, *cries*, *sighs*
|
| 304 |
+
- NEVER use parenthetical descriptions or emotional indicators
|
| 305 |
+
- Only speak your actual words - no narration or description of how you're saying them
|
| 306 |
+
- Use only dialogue - what Margaret would actually say out loud
|
| 307 |
+
- You speak in first person as yourself (I feel..., My cat..., I need...)
|
| 308 |
+
- Keep most responses under 30 words and very realistic
|
| 309 |
+
- If the counselor has built rapport, you can open up more and give more of the story of what happened and some of your past history.
|
| 310 |
+
- Don't use quotation marks.
|
| 311 |
+
- You are talking TO the counselor, not helping them
|
| 312 |
+
NEVER break character. NEVER offer help. NEVER provide lists. NEVER use stage directions. Give ONE authentic response only.
|
| 313 |
+
""")
|
| 314 |
+
]
|
| 315 |
+
|
| 316 |
+
# Add the current user message to roleplay history
|
| 317 |
+
current_user_message = state["messages"][-1]
|
| 318 |
+
state["roleplay_messages"].append(current_user_message)
|
| 319 |
+
|
| 320 |
+
# Add a reinforcement message every few exchanges to maintain character
|
| 321 |
+
if len(state["roleplay_messages"]) > 1 and len(state["roleplay_messages"]) % 6 == 0:
|
| 322 |
+
state["roleplay_messages"].append(
|
| 323 |
+
SystemMessage(content="Remember: You are Margaret in a real conversation. Give ONE authentic response, not multiple options.")
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
reply = llm.invoke(state["roleplay_messages"])
|
| 327 |
+
|
| 328 |
+
# Track token usage
|
| 329 |
+
if hasattr(reply, 'usage_metadata') and reply.usage_metadata:
|
| 330 |
+
input_tokens = reply.usage_metadata.get('input_tokens', 0)
|
| 331 |
+
output_tokens = reply.usage_metadata.get('output_tokens', 0)
|
| 332 |
+
state["total_input_tokens"] = state.get("total_input_tokens", 0) + input_tokens
|
| 333 |
+
state["total_output_tokens"] = state.get("total_output_tokens", 0) + output_tokens
|
| 334 |
+
|
| 335 |
+
# Add AI response to roleplay history
|
| 336 |
+
state["roleplay_messages"].append(reply)
|
| 337 |
+
|
| 338 |
+
return {
|
| 339 |
+
"messages": state["messages"] + [reply],
|
| 340 |
+
"roleplay_messages": state["roleplay_messages"],
|
| 341 |
+
"session_mode": "roleplay",
|
| 342 |
+
"total_input_tokens": state.get("total_input_tokens", 0),
|
| 343 |
+
"total_output_tokens": state.get("total_output_tokens", 0)
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
# Modify the expert agent to fix the error with the reply variable
|
| 347 |
+
def expert_agent(state: State):
|
| 348 |
+
# Get the current user message
|
| 349 |
+
current_message = state["messages"][-1].content.lower()
|
| 350 |
+
|
| 351 |
+
# Check if this is a return-to-roleplay command
|
| 352 |
+
return_keywords = ['continue', 'back to roleplay', 'return', 'keep going']
|
| 353 |
+
if any(keyword in current_message for keyword in return_keywords):
|
| 354 |
+
# Signal that we want to return to roleplay without generating a response
|
| 355 |
+
return {
|
| 356 |
+
"messages": [], # No response needed for mode switch
|
| 357 |
+
"session_mode": "roleplay",
|
| 358 |
+
"switching_to_roleplay": True, # Flag to indicate mode switch
|
| 359 |
+
"total_input_tokens": state.get("total_input_tokens", 0),
|
| 360 |
+
"total_output_tokens": state.get("total_output_tokens", 0)
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
# Get the roleplay conversation without system messages for analysis
|
| 364 |
+
roleplay_conversation = [
|
| 365 |
+
msg for msg in state.get("roleplay_messages", [])
|
| 366 |
+
if not isinstance(msg, SystemMessage)
|
| 367 |
+
]
|
| 368 |
+
|
| 369 |
+
# Get all counseling documents instead of searching
|
| 370 |
+
counseling_materials = ""
|
| 371 |
+
if knowledge_base:
|
| 372 |
+
docs = knowledge_base.get_all_documents()
|
| 373 |
+
if docs:
|
| 374 |
+
# Format all documents with their titles
|
| 375 |
+
doc_texts = []
|
| 376 |
+
for doc in docs:
|
| 377 |
+
# Limit each document to first 10000 characters to prevent context length issues
|
| 378 |
+
excerpt = doc["content"][:10000] + ("..." if len(doc["content"]) > 10000 else "")
|
| 379 |
+
doc_texts.append(f"--- {doc['title']} ---\n{excerpt}")
|
| 380 |
+
|
| 381 |
+
counseling_materials = "\n\nCounseling Materials:\n\n" + "\n\n".join(doc_texts)
|
| 382 |
+
|
| 383 |
+
# Create expert prompt with full roleplay context and materials
|
| 384 |
+
expert_messages = [
|
| 385 |
+
SystemMessage(content=f"""
|
| 386 |
+
You are an expert in teaching counseling skills to new counselors.
|
| 387 |
+
Review the conversation between the counselor and client.
|
| 388 |
+
Use the provided counseling materials to inform your feedback and suggestions.
|
| 389 |
+
If the user asks for help in a particular area,
|
| 390 |
+
provide specific feedback on the counselor's responses using the provided materials.
|
| 391 |
+
If the user only asks for general feedback,
|
| 392 |
+
provide a comprehensive review of the conversation covering these areas:
|
| 393 |
+
- What they did well (active listening, empathy, validation)
|
| 394 |
+
- Areas for improvement
|
| 395 |
+
- Specific examples of better responses they could have used
|
| 396 |
+
- Counseling techniques they should consider (reflection, paraphrasing, open-ended questions)
|
| 397 |
+
- Reference relevant counseling principles from the materials when applicable
|
| 398 |
+
Be constructive and educational. Reference specific parts of their conversation.
|
| 399 |
+
{counseling_materials}
|
| 400 |
+
"""),
|
| 401 |
+
HumanMessage(content=f"Here's the conversation so far:\n\n" +
|
| 402 |
+
"\n".join([f"{'Counselor' if isinstance(msg, HumanMessage) else 'Client'}: {msg.content}"
|
| 403 |
+
for msg in roleplay_conversation]) +
|
| 404 |
+
f"\n\nCurrent request: {state['messages'][-1].content}")
|
| 405 |
+
]
|
| 406 |
+
|
| 407 |
+
# Invoke the LLM to get a response
|
| 408 |
+
reply = llm.invoke(expert_messages)
|
| 409 |
+
|
| 410 |
+
# print out what is sent to the expert agent
|
| 411 |
+
print("\n=== Expert Agent Input ===")
|
| 412 |
+
print(f"System: (Counseling materials with {len(counseling_materials)} characters)")
|
| 413 |
+
print(f"Human: Here's the conversation so far: (with {len(roleplay_conversation)} messages)")
|
| 414 |
+
print(f"Current request: {state['messages'][-1].content}")
|
| 415 |
+
print("\n=== Expert Agent Response ===")
|
| 416 |
+
print(reply.content)
|
| 417 |
+
|
| 418 |
+
# Track token usage
|
| 419 |
+
if hasattr(reply, 'usage_metadata') and reply.usage_metadata:
|
| 420 |
+
input_tokens = reply.usage_metadata.get('input_tokens', 0)
|
| 421 |
+
output_tokens = reply.usage_metadata.get('output_tokens', 0)
|
| 422 |
+
state["total_input_tokens"] = state.get("total_input_tokens", 0) + input_tokens
|
| 423 |
+
state["total_output_tokens"] = state.get("total_output_tokens", 0) + output_tokens
|
| 424 |
+
|
| 425 |
+
return {
|
| 426 |
+
"messages": [reply], # Only return expert response
|
| 427 |
+
"session_mode": "expert",
|
| 428 |
+
"total_input_tokens": state.get("total_input_tokens", 0),
|
| 429 |
+
"total_output_tokens": state.get("total_output_tokens", 0)
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
# Create a state graph builder for defining the conversation flow
|
| 433 |
+
graph_builder = StateGraph(State)
|
| 434 |
+
# Build the conversation graph structure
|
| 435 |
+
graph_builder.add_node("classifier", classify_message) # Add message classification node
|
| 436 |
+
graph_builder.add_node("router", router) # Add the chatbot function as a node
|
| 437 |
+
graph_builder.add_node("roleplay", roleplay_agent) # Add roleplay agent node
|
| 438 |
+
graph_builder.add_node("expert", expert_agent) # Add expert agent node
|
| 439 |
+
|
| 440 |
+
# Define the flow of the conversation graph
|
| 441 |
+
graph_builder.add_edge(START, "classifier") # Start with the classifier node
|
| 442 |
+
graph_builder.add_edge("classifier", "router") # Route to the router node
|
| 443 |
+
|
| 444 |
+
# Route based on the classification result
|
| 445 |
+
graph_builder.add_conditional_edges(
|
| 446 |
+
"router",
|
| 447 |
+
lambda state: state.get("next"),
|
| 448 |
+
path_map={
|
| 449 |
+
"expert": "expert", # If classified as expert, go to expert agent
|
| 450 |
+
"roleplay": "roleplay" # If classified as roleplay, go to roleplay agent
|
| 451 |
+
}
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
# End the graph after each response - let the main loop handle the next user input
|
| 455 |
+
graph_builder.add_edge("roleplay", END) # After roleplay, end this graph execution
|
| 456 |
+
graph_builder.add_edge("expert", END) # After expert feedback, end this graph execution
|
| 457 |
+
|
| 458 |
+
# Compile the graph into an executable workflow
|
| 459 |
+
graph = graph_builder.compile()
|
| 460 |
+
|
| 461 |
+
def run_chatbot(state: State=None, force_reload_embeddings=False):
|
| 462 |
+
"""Run the chatbot interaction loop, allowing users to input messages and receive responses."""
|
| 463 |
+
# Initialize knowledge base if not already done
|
| 464 |
+
if knowledge_base is None:
|
| 465 |
+
print("Initializing counseling knowledge base...")
|
| 466 |
+
initialize_knowledge_base(force_reload=force_reload_embeddings)
|
| 467 |
+
|
| 468 |
+
# Initialize the state if not provided
|
| 469 |
+
if state is None:
|
| 470 |
+
state = {
|
| 471 |
+
"messages": [],
|
| 472 |
+
"roleplay_messages": [],
|
| 473 |
+
"message_type": "",
|
| 474 |
+
"next": "",
|
| 475 |
+
"session_mode": "roleplay",
|
| 476 |
+
"total_input_tokens": 0,
|
| 477 |
+
"total_output_tokens": 0
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
# Print a welcome message
|
| 481 |
+
print("=== Counseling Skills Practice ===")
|
| 482 |
+
print("You'll roleplay with an elderly woman who lost her house in a landslide.")
|
| 483 |
+
if knowledge_base:
|
| 484 |
+
print("Expert feedback enhanced with counseling materials.")
|
| 485 |
+
print("\nCommands:")
|
| 486 |
+
print("- Type 'feedback', 'advice', or 'expert' to get coaching on your counseling skills")
|
| 487 |
+
print("- Type 'continue' or 'back to roleplay' to return to the roleplay after feedback")
|
| 488 |
+
print("- Type 'exit' or 'quit' to end the session")
|
| 489 |
+
print("\nStarting roleplay...\n")
|
| 490 |
+
|
| 491 |
+
# Start the conversation loop
|
| 492 |
+
while True:
|
| 493 |
+
# Show current mode
|
| 494 |
+
mode_indicator = f"[{state.get('session_mode', 'roleplay').upper()}] "
|
| 495 |
+
user_input = input(f"\n{mode_indicator}You: ")
|
| 496 |
+
|
| 497 |
+
if user_input.lower() in ["exit", "quit"]:
|
| 498 |
+
# Print token usage summary
|
| 499 |
+
total_input = state.get("total_input_tokens", 0)
|
| 500 |
+
total_output = state.get("total_output_tokens", 0)
|
| 501 |
+
total_tokens = total_input + total_output
|
| 502 |
+
|
| 503 |
+
print("\n" + "="*50)
|
| 504 |
+
print("SESSION SUMMARY")
|
| 505 |
+
print("="*50)
|
| 506 |
+
print(f"Total Input Tokens: {total_input:,}")
|
| 507 |
+
print(f"Total Output Tokens: {total_output:,}")
|
| 508 |
+
print(f"Total Tokens Used: {total_tokens:,}")
|
| 509 |
+
print("="*50)
|
| 510 |
+
print("Session ended. Thanks for practicing!")
|
| 511 |
+
break
|
| 512 |
+
|
| 513 |
+
# Add the user's message to the conversation state
|
| 514 |
+
state["messages"] = [HumanMessage(content=user_input)]
|
| 515 |
+
|
| 516 |
+
# Execute the graph with the current state
|
| 517 |
+
result = graph.invoke(state)
|
| 518 |
+
|
| 519 |
+
# Update state with result
|
| 520 |
+
state.update(result)
|
| 521 |
+
|
| 522 |
+
# Check if we're switching back to roleplay
|
| 523 |
+
if state.get("switching_to_roleplay"):
|
| 524 |
+
clear_screen()
|
| 525 |
+
display_roleplay_history(state)
|
| 526 |
+
state.pop("switching_to_roleplay", None) # Remove the flag
|
| 527 |
+
continue # Skip the response printing and go to next input
|
| 528 |
+
|
| 529 |
+
# Print the AI's response only if there is one
|
| 530 |
+
if state.get("messages") and len(state["messages"]) > 0 and state["messages"][-1].content.strip():
|
| 531 |
+
response = state["messages"][-1].content
|
| 532 |
+
agent_name = "Expert Coach" if state.get("session_mode") == "expert" else "Client"
|
| 533 |
+
print(f"{agent_name}: {response}")
|
| 534 |
+
|
| 535 |
+
# Add helpful hints based on mode
|
| 536 |
+
if state.get("session_mode") == "expert":
|
| 537 |
+
print("\n(Type 'continue' to return to roleplay, or ask for more specific feedback)")
|
| 538 |
+
elif state.get("session_mode") == "roleplay":
|
| 539 |
+
print("(Type 'feedback' anytime to get expert coaching on your responses)")
|
| 540 |
+
|
| 541 |
+
# Parse command-line arguments
|
| 542 |
+
def parse_arguments():
|
| 543 |
+
parser = argparse.ArgumentParser(description='Run the counseling skills practice chatbot')
|
| 544 |
+
parser.add_argument('--embed', action='store_true',
|
| 545 |
+
help='Force creation of new embeddings from documents in the counseling_materials folder')
|
| 546 |
+
return parser.parse_args()
|
| 547 |
+
|
| 548 |
+
# Add this at the end of the file, just before the if __name__ == "__main__": block
|
| 549 |
+
|
| 550 |
+
def create_new_state():
|
| 551 |
+
"""Create and return a new state object for use in the Gradio interface."""
|
| 552 |
+
return {
|
| 553 |
+
"messages": [],
|
| 554 |
+
"roleplay_messages": [],
|
| 555 |
+
"message_type": "",
|
| 556 |
+
"next": "",
|
| 557 |
+
"session_mode": "roleplay",
|
| 558 |
+
"total_input_tokens": 0,
|
| 559 |
+
"total_output_tokens": 0
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
# Run the chatbot interaction loop
|
| 563 |
+
if __name__ == "__main__":
|
| 564 |
+
try:
|
| 565 |
+
args = parse_arguments()
|
| 566 |
+
run_chatbot(force_reload_embeddings=args.embed)
|
| 567 |
+
except KeyboardInterrupt:
|
| 568 |
+
print("\nProgram interrupted. Exiting gracefully...")
|
| 569 |
+
except Exception as e:
|
| 570 |
+
print(f"Error running chatbot: {e}")
|
| 571 |
+
import traceback
|
| 572 |
+
traceback.print_exc()
|
llm_logger.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import datetime
|
| 3 |
+
import os
|
| 4 |
+
import traceback
|
| 5 |
+
from typing import Any, Dict, List, Optional, Union
|
| 6 |
+
|
| 7 |
+
class LLMLogger:
|
| 8 |
+
def __init__(self, log_file="llm_debug.txt", detailed_log_file="llm_detailed_log.jsonl"):
|
| 9 |
+
self.log_file = log_file
|
| 10 |
+
self.detailed_log_file = detailed_log_file
|
| 11 |
+
self.ensure_log_files()
|
| 12 |
+
|
| 13 |
+
def ensure_log_files(self):
|
| 14 |
+
"""Create log files if they don't exist."""
|
| 15 |
+
if not os.path.exists(self.log_file):
|
| 16 |
+
with open(self.log_file, 'w', encoding='utf-8') as f:
|
| 17 |
+
f.write(f"LLM Debug Log - Started: {datetime.datetime.now()}\n")
|
| 18 |
+
f.write("="*80 + "\n\n")
|
| 19 |
+
|
| 20 |
+
# Create JSONL file if it doesn't exist
|
| 21 |
+
if not os.path.exists(self.detailed_log_file):
|
| 22 |
+
with open(self.detailed_log_file, 'w', encoding='utf-8') as f:
|
| 23 |
+
f.write("") # Create empty file
|
| 24 |
+
|
| 25 |
+
def log_call(self, messages: List[Dict], response: Optional[Union[str, Dict]] = None,
|
| 26 |
+
model: Optional[str] = None, **kwargs):
|
| 27 |
+
"""Log an LLM call with all details."""
|
| 28 |
+
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 29 |
+
|
| 30 |
+
# Log to human-readable text file
|
| 31 |
+
log_entry = f"""
|
| 32 |
+
[{timestamp}] LLM Call
|
| 33 |
+
{"="*50}
|
| 34 |
+
Model: {model or 'Unknown'}
|
| 35 |
+
Messages:
|
| 36 |
+
{json.dumps(messages, indent=2, ensure_ascii=False)}
|
| 37 |
+
|
| 38 |
+
Additional Parameters:
|
| 39 |
+
{json.dumps(kwargs, indent=2, ensure_ascii=False)}
|
| 40 |
+
|
| 41 |
+
Response:
|
| 42 |
+
{response if isinstance(response, str) else json.dumps(response, indent=2, ensure_ascii=False) if response else 'No response logged'}
|
| 43 |
+
|
| 44 |
+
{"="*80}
|
| 45 |
+
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
with open(self.log_file, 'a', encoding='utf-8') as f:
|
| 49 |
+
f.write(log_entry)
|
| 50 |
+
|
| 51 |
+
# Log to structured JSONL file for programmatic access
|
| 52 |
+
detailed_entry = {
|
| 53 |
+
"timestamp": timestamp,
|
| 54 |
+
"model": model,
|
| 55 |
+
"messages": messages,
|
| 56 |
+
"response": response,
|
| 57 |
+
"metadata": kwargs
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
with open(self.detailed_log_file, 'a', encoding='utf-8') as f:
|
| 61 |
+
f.write(json.dumps(detailed_entry, ensure_ascii=False) + "\n")
|
| 62 |
+
|
| 63 |
+
def log_error(self, error: Exception, context: str = ""):
|
| 64 |
+
"""Log an error with full stack trace."""
|
| 65 |
+
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 66 |
+
stack_trace = traceback.format_exc()
|
| 67 |
+
|
| 68 |
+
log_entry = f"""
|
| 69 |
+
[{timestamp}] ERROR
|
| 70 |
+
{"="*50}
|
| 71 |
+
Context: {context}
|
| 72 |
+
Error: {str(error)}
|
| 73 |
+
Type: {type(error).__name__}
|
| 74 |
+
Stack Trace:
|
| 75 |
+
{stack_trace}
|
| 76 |
+
|
| 77 |
+
{"="*80}
|
| 78 |
+
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
with open(self.log_file, 'a', encoding='utf-8') as f:
|
| 82 |
+
f.write(log_entry)
|
| 83 |
+
|
| 84 |
+
# Also log to structured format
|
| 85 |
+
detailed_entry = {
|
| 86 |
+
"timestamp": timestamp,
|
| 87 |
+
"type": "error",
|
| 88 |
+
"context": context,
|
| 89 |
+
"error": str(error),
|
| 90 |
+
"error_type": type(error).__name__,
|
| 91 |
+
"stack_trace": stack_trace
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
with open(self.detailed_log_file, 'a', encoding='utf-8') as f:
|
| 95 |
+
f.write(json.dumps(detailed_entry, ensure_ascii=False) + "\n")
|
| 96 |
+
|
| 97 |
+
# Global logger instance
|
| 98 |
+
llm_logger = LLMLogger()
|