Repository navigation
Expand file tree
/
Copy pathrun.py
More file actions
209 lines (166 loc) · 7.06 KB
/
Copy pathrun.py
File metadata and controls
209 lines (166 loc) · 7.06 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
#!/usr/bin/env python3
"""
GenAI Testing Tutorial - RAG Chatbot Application
Entry point for running the Flask application
"""
import os
import sys
import subprocess
# Add the app directory to the Python path
sys.path.insert(0, os.path.dirname(__file__))
def format_pip_install_cmd() -> str:
"""Return a pip install command that targets the active interpreter."""
return f'"{sys.executable}" -m pip install -r requirements.txt'
def get_project_venv_python() -> str | None:
"""Return project venv Python path when present, otherwise None."""
base_dir = os.path.dirname(__file__)
if os.name == "nt":
candidates = [
os.path.join(base_dir, ".venv", "Scripts", "python.exe"),
]
else:
candidates = [
os.path.join(base_dir, ".venv", "bin", "python"),
]
for candidate in candidates:
if os.path.exists(candidate):
return candidate
return None
def maybe_relaunch_with_project_venv():
"""Relaunch this script with project venv Python when available."""
# Avoid relaunch loops.
if os.getenv("TESTING_AI_SKIP_VENV_REDIRECT") == "1":
return
venv_python = get_project_venv_python()
if not venv_python:
return
current_python = os.path.abspath(sys.executable)
if os.path.abspath(venv_python) == current_python:
return
print("Switching to project virtual environment interpreter...")
env = os.environ.copy()
env["TESTING_AI_SKIP_VENV_REDIRECT"] = "1"
cmd = [venv_python, os.path.abspath(__file__), *sys.argv[1:]]
rc = subprocess.call(cmd, env=env)
sys.exit(rc)
def preflight_ollama(ollama_host: str, ollama_model: str):
"""Perform a quick connectivity check to Ollama before app startup."""
import requests
tags_url = f"{ollama_host.rstrip('/')}/api/tags"
try:
response = requests.get(tags_url, timeout=8)
response.raise_for_status()
models = response.json().get("models", [])
model_names = {m.get("name") for m in models if isinstance(m, dict)}
if ollama_model not in model_names:
print("Ollama is reachable, but configured model was not found:")
print(f" - Configured model: {ollama_model}")
print(" - Next step: run `ollama pull " + ollama_model + "`")
else:
print(f"Ollama preflight passed: {ollama_model} is available")
except Exception as exc:
print("Ollama preflight warning: unable to reach configured OLLAMA_HOST")
print(f" - Host: {ollama_host}")
print(f" - Details: {exc}")
print(" - Next step: ensure Ollama is running and OLLAMA_HOST is correct")
def classroom_preflight():
"""Warm the Ask and single-agent paths before a classroom session starts."""
import requests
enabled = os.getenv("CLASSROOM_PREWARM_ENABLED", "false").lower() in {
"1", "true", "yes", "on"
}
if not enabled:
return
prompt = "What are the key challenges in testing GenAI applications?"
print("Preparing Ask and Agent modes for the classroom session...")
try:
from app.main import agentic_pipeline, initialize_rag
if initialize_rag():
print("Ask mode is ready.")
else:
print("Ask mode preflight did not complete; it will retry on the first request.")
ollama_host = os.getenv("OLLAMA_HOST", "http://127.0.0.1:11434").rstrip("/")
try:
requests.get(f"{ollama_host}/api/tags", timeout=2).raise_for_status()
except Exception as exc:
print(f"Agent mode preflight deferred: Ollama is not ready ({exc}).")
return
agentic_pipeline.process(
prompt,
session_id="classroom-startup-prewarm",
include_trace=False,
crew_mode=False,
exercise_number=None,
)
print("Agent mode is ready.")
except Exception as exc:
print(f"Classroom preflight warning: {exc}")
print("The app will remain available and retry initialization on demand.")
if __name__ == '__main__':
maybe_relaunch_with_project_venv()
try:
from dotenv import load_dotenv
except ModuleNotFoundError as e:
missing = getattr(e, "name", "unknown module")
print("Missing required Python dependency:")
print(f" - {missing}")
print("\nInstall project dependencies with your current interpreter:")
print(f" {format_pip_install_cmd()}")
venv_python = get_project_venv_python()
if venv_python:
print("\nOr run using the project virtual environment interpreter:")
print(f" \"{venv_python}\" -m pip install -r requirements.txt")
print(f" \"{venv_python}\" run.py")
print("\nThen run this command again.")
sys.exit(1)
# Load environment variables
load_dotenv()
# Import and run the Flask app
try:
import app.main as app_main
except ModuleNotFoundError as e:
missing = getattr(e, "name", "unknown module")
print("Missing required Python dependency:")
print(f" - {missing}")
print("\nInstall project dependencies with your current interpreter:")
print(f" {format_pip_install_cmd()}")
venv_python = get_project_venv_python()
if venv_python:
print("\nOr run using the project virtual environment interpreter:")
print(f" \"{venv_python}\" -m pip install -r requirements.txt")
print(f" \"{venv_python}\" run.py")
print("\nThen run this command again.")
sys.exit(1)
if __name__ == '__main__':
# Local-first runtime: Ollama defaults come from .env but do not require secrets.
ollama_model = os.getenv('OLLAMA_MODEL', 'llama3.2:1b')
ollama_host = os.getenv('OLLAMA_HOST', 'http://127.0.0.1:11434')
preflight_ollama(ollama_host, ollama_model)
rag_warmup_completed = True
if os.getenv('RAG_WARMUP_ENABLED', 'false').lower() in {'1', 'true', 'yes', 'on'}:
print("Preparing RAG and Ollama before accepting classroom requests...")
rag_ready = app_main.initialize_rag()
rag_warmup_completed = bool(
app_main.rag_pipeline
and app_main.rag_pipeline.stats.get('warmup_completed', False)
)
if rag_ready and rag_warmup_completed:
print("RAG and Ollama startup warmup completed.")
else:
print("RAG startup warmup did not complete; the app will retry on demand.")
if rag_warmup_completed:
app_main.warmup_agentic_pipeline()
else:
print("Agent/crew startup warmup deferred because Ollama warmup did not complete.")
print("Starting GenAI Testing Tutorial Application...")
print(f"Documents directory: {os.path.join(os.path.dirname(__file__), 'data', 'documents')}")
print(f"Environment: {os.getenv('FLASK_ENV', 'development')}")
print(f"LLM Provider: Ollama ({ollama_model}) @ {ollama_host}")
print(f"Server will start on: http://localhost:{os.getenv('FLASK_PORT', 5000)}")
print("\n" + "="*50)
# Start the Flask application
app_main.app.run(
host='0.0.0.0',
port=int(os.getenv('FLASK_PORT', 5000)),
debug=os.getenv('FLASK_DEBUG', 'True').lower() == 'true'
)