|
1 | 1 | import json |
| 2 | +from datetime import datetime |
2 | 3 |
|
3 | 4 | import tornado |
4 | 5 | from jupyter_server.base.handlers import APIHandler |
@@ -36,6 +37,31 @@ async def post(self): |
36 | 37 | self.set_header("X-Accel-Buffering", "no") |
37 | 38 |
|
38 | 39 | system_prompt = self.settings.get("jupyter_ai_tutor.system_prompt", "") |
| 40 | + debug_mode = self.settings.get("jupyter_ai_tutor.debug", False) |
| 41 | + prompt_file = None |
| 42 | + answer_file = None |
| 43 | + accumulated_response = "" |
| 44 | + |
| 45 | + if debug_mode: |
| 46 | + import os |
| 47 | + debug_dir = "/tmp/jupyter-ai-tutor" |
| 48 | + try: |
| 49 | + os.makedirs(debug_dir, exist_ok=True) |
| 50 | + except Exception as e: |
| 51 | + self.log.error(f"Failed to create debug directory {debug_dir}: {e}") |
| 52 | + timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") |
| 53 | + prompt_file = f"{debug_dir}/{timestamp}_jupyter_tutor_prompt.txt" |
| 54 | + answer_file = f"{debug_dir}/{timestamp}_jupyter_tutor_answer.txt" |
| 55 | + try: |
| 56 | + with open(prompt_file, "w", encoding="utf-8") as f: |
| 57 | + f.write("=== SYSTEM PROMPT ===\n") |
| 58 | + f.write(system_prompt) |
| 59 | + f.write("\n=====================\n\n") |
| 60 | + f.write("=== USER MESSAGE ===\n") |
| 61 | + f.write(message_body) |
| 62 | + f.write("\n====================\n") |
| 63 | + except Exception as e: |
| 64 | + self.log.error(f"Failed to write tutor debug prompt: {e}") |
39 | 65 |
|
40 | 66 | try: |
41 | 67 | from jupyter_ai_jupyternaut.jupyternaut.chat_models import ChatLiteLLM |
@@ -63,10 +89,25 @@ async def post(self): |
63 | 89 | ) |
64 | 90 | ) |
65 | 91 | if text: |
| 92 | + if debug_mode: |
| 93 | + accumulated_response += text |
66 | 94 | self.write(f"data: {json.dumps({'text': text})}\n\n") |
67 | 95 | self.flush() |
68 | 96 |
|
| 97 | + if debug_mode and answer_file: |
| 98 | + try: |
| 99 | + with open(answer_file, "w", encoding="utf-8") as f: |
| 100 | + f.write(accumulated_response) |
| 101 | + except Exception as e: |
| 102 | + self.log.error(f"Failed to write tutor debug answer: {e}") |
| 103 | + |
69 | 104 | except StreamClosedError: |
| 105 | + if debug_mode and answer_file and accumulated_response: |
| 106 | + try: |
| 107 | + with open(answer_file, "w", encoding="utf-8") as f: |
| 108 | + f.write(accumulated_response) |
| 109 | + except Exception as e: |
| 110 | + pass |
70 | 111 | return # Client disconnected; stop streaming |
71 | 112 | except Exception as e: |
72 | 113 | self.log.exception("Error during tutor LLM call") |
|
0 commit comments