-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathauto-setup.py
More file actions
executable file
Β·2034 lines (1694 loc) Β· 73.4 KB
/
Copy pathauto-setup.py
File metadata and controls
executable file
Β·2034 lines (1694 loc) Β· 73.4 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""MLflow Demo Automated Setup Script.
This script automates the entire end-to-end setup process for the MLflow demo application,
including creating Databricks resources, configuring environment, loading sample data,
and deploying the application.
Usage:
python auto-setup.py [options]
Options:
--dry-run Show what would be created without actually creating resources
--resume Resume from previous failed/interrupted setup
--reset Reset all progress and start fresh
--validate-only Only run validation checks
--help Show this help message
"""
import argparse
import os
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import Any, Dict, List
from databricks.sdk import WorkspaceClient
from databricks.sdk.errors import NotFound, PermissionDenied
from dotenv import load_dotenv
# Add automation directory to path
automation_dir = Path(__file__).parent / 'automation'
sys.path.insert(0, str(automation_dir))
# Import after sys.path modification
from environment_detector import EnvironmentDetector # noqa: E402
from progress_tracker import ProgressTracker # noqa: E402
from resource_manager import DatabricksResourceManager # noqa: E402
from validation import SetupValidator # noqa: E402
class Spinner:
"""Simple spinner to show progress during long operations."""
def __init__(self, message: str):
self.message = message
self.spinning = False
self.thread = None
self.spinner_chars = 'β β β Ήβ Έβ Όβ ΄β ¦β §β β '
def start(self):
"""Start the spinner."""
self.spinning = True
self.thread = threading.Thread(target=self._spin)
self.thread.start()
def stop(self, success_message: str = None):
"""Stop the spinner."""
self.spinning = False
if self.thread:
self.thread.join()
# Clear the line and show completion
print(f'\r{" " * (len(self.message) + 10)}', end='') # Clear line
if success_message:
print(f'\rβ
{success_message}')
else:
print(f'\rβ
{self.message}')
def _spin(self):
"""Internal spinner loop."""
i = 0
while self.spinning:
print(
f'\r{self.spinner_chars[i % len(self.spinner_chars)]} {self.message}', end='', flush=True
)
time.sleep(0.1)
i += 1
class AutoSetup:
"""Main orchestrator for automated MLflow demo setup."""
def __init__(self, dry_run: bool = False):
"""Initialize the auto setup.
Args:
dry_run: If True, only show what would be done without executing
"""
self.dry_run = dry_run
self.project_root = Path(__file__).parent
# Initialize components (defer authentication until actually running setup)
self.client = None
self.resource_manager = None
self.env_detector = None
self.validator = None
self.progress = ProgressTracker(self.project_root)
# Store configuration and created resources
self.config = {}
self.created_resources = {}
self.detected_settings = {}
def _initialize_databricks_components(self, skip_auth_prompts: bool = False) -> bool:
"""Initialize Databricks components with authentication."""
if not self.dry_run:
# Handle authentication first
if not self._ensure_databricks_auth(skip_prompts=skip_auth_prompts):
return False
try:
self.client = WorkspaceClient()
self.resource_manager = DatabricksResourceManager(self.client)
self.env_detector = EnvironmentDetector(self.client)
self.validator = SetupValidator(self.client)
return True
except Exception as e:
print(f'β Failed to initialize Databricks SDK: {e}')
return False
else:
# For dry run, keep placeholder components
return True
def _test_create_schema_permission(self, catalog_name: str) -> bool:
"""Test if user can actually create schemas in this catalog."""
import os
from databricks.sdk.errors import PermissionDenied
# Try to create a test schema with a unique name
test_schema_name = f'test_perms_{int(os.urandom(4).hex(), 16)}'
try:
# Try to create the test schema
self.client.schemas.create(
name=test_schema_name,
catalog_name=catalog_name,
comment='Temporary test schema for permission verification',
)
# If successful, clean up immediately
try:
self.client.schemas.delete(f'{catalog_name}.{test_schema_name}')
except Exception:
pass # Cleanup failed but permission test succeeded
return True
except PermissionDenied:
return False
except Exception:
return False # Any other error means we can't create schemas
def _get_available_catalogs_with_permissions(self) -> Dict[str, str]:
"""Get catalogs where user has required permissions (USE CATALOG + CREATE SCHEMA)."""
available_catalogs = {}
try:
spinner = Spinner('Loading available catalogs...')
spinner.start()
try:
catalogs = list(self.client.catalogs.list())
spinner.stop('Found catalogs')
except Exception as e:
spinner.stop()
raise e
# Limit to first 50 catalogs to avoid timeout issues
# Most users won't need to check thousands of catalogs
catalog_sample = catalogs[:50] if len(catalogs) > 50 else catalogs
print(
f'β
Found {len(catalogs)} catalogs, verifying CREATE SCHEMA permissions on '
f'first {len(catalog_sample)}'
)
print('π This may take a moment as we test actual CREATE SCHEMA permissions...')
verified_count = 0
for i, catalog in enumerate(catalog_sample):
catalog_name = catalog.name
# Show progress for long operations
if i % 10 == 0 and i > 0:
print(
f' Verified {verified_count} usable catalogs after checking '
f'{i}/{len(catalog_sample)}...'
)
try:
# First check if we can list schemas (USE CATALOG permission)
list(self.client.schemas.list(catalog_name=catalog_name))
# Then test CREATE SCHEMA permission by actually trying to create a schema
if self._test_create_schema_permission(catalog_name):
available_catalogs[catalog_name] = 'VERIFIED: USE CATALOG + CREATE SCHEMA'
verified_count += 1
print(f' β
{catalog_name} - CREATE SCHEMA verified')
# Stop after finding a reasonable number to avoid excessive API calls
if verified_count >= 10:
print(
f' Found {verified_count} verified catalogs, stopping search to avoid timeouts'
)
break
except Exception:
# Can't access this catalog
continue
print(f'β
Found {len(available_catalogs)} catalogs with verified CREATE SCHEMA permissions')
except Exception as e:
print(f'β οΈ Could not verify catalog permissions: {e}')
return available_catalogs
def _get_available_schemas_in_catalog(self, catalog_name: str) -> Dict[str, str]:
"""Get schemas in a catalog where user has required permissions."""
available_schemas = {}
try:
spinner = Spinner(f"Loading schemas in catalog '{catalog_name}'...")
spinner.start()
try:
schemas = list(self.client.schemas.list(catalog_name=catalog_name))
spinner.stop(f"Found {len(schemas)} schemas in '{catalog_name}'")
except Exception as e:
spinner.stop()
raise e
if not schemas:
print(f" No schemas found in '{catalog_name}'")
return available_schemas
print(f'π Checking permissions on {len(schemas)} schemas...')
for i, schema in enumerate(schemas):
schema_name = schema.name
full_schema_name = f'{catalog_name}.{schema_name}'
# Show progress for long operations
if len(schemas) > 10 and i % 5 == 0 and i > 0:
print(f' Checked {i}/{len(schemas)} schemas...')
# Check if user has required permissions: MANAGE and CREATE TABLE
has_manage = False
has_create_table = False
try:
# Get schema info to check basic access
schema_info = self.client.schemas.get(full_schema_name)
# Check for MANAGE permission by trying to get effective permissions
try:
# Try to get grants/permissions on the schema
# This is an approximation - checking if we can read schema grants
grants = list(
self.client.grants.get_effective(securable_type='schema', full_name=full_schema_name)
)
# Look for our permissions in the grants
current_user = self.client.current_user.me()
user_email = current_user.user_name if hasattr(current_user, 'user_name') else None
for grant in grants:
# Check if this grant applies to current user
principal = getattr(grant, 'principal', '')
privileges = getattr(grant, 'privileges', [])
if user_email and user_email in principal:
for privilege in privileges:
if privilege == 'ALL_PRIVILEGES' or privilege == 'OWNER':
has_manage = True
has_create_table = True
break
elif privilege == 'CREATE_TABLE':
has_create_table = True
elif privilege == 'MANAGE':
has_manage = True
# If we can't determine from grants, try alternative check
if not (has_manage and has_create_table):
# Try to list tables as a proxy for having reasonable access
try:
list(self.client.tables.list(catalog_name=catalog_name, schema_name=schema_name))
# If we can list tables, assume we have at least some useful access
has_create_table = True
except Exception:
pass
except Exception:
# If we can't check grants, try a simpler approach
# Try to list tables as a proxy for having reasonable access
try:
list(self.client.tables.list(catalog_name=catalog_name, schema_name=schema_name))
# If we can list tables, assume we have reasonable access
has_create_table = True
has_manage = True # Assume if we can list tables, we have good access
except Exception:
pass
# Determine permission level
if has_manage and has_create_table:
available_schemas[schema_name] = 'MANAGE + CREATE TABLE'
elif has_create_table:
available_schemas[schema_name] = 'CREATE TABLE only'
elif schema_info:
# We can see the schema but don't have required permissions
continue # Don't include schemas without required permissions
except Exception:
# Can't access schema at all
continue
print(f'β
Found {len(available_schemas)} accessible schemas with permissions')
except Exception as e:
print(f'β οΈ Could not list schemas in {catalog_name}: {e}')
return available_schemas
def _prompt_for_catalog_selection(self, suggested_catalog: str = None) -> str:
"""Interactive catalog selection with permission checking."""
print('\nπ Unity Catalog Selection')
# Get available catalogs
available_catalogs = self._get_available_catalogs_with_permissions()
if not available_catalogs:
print('β No catalogs found with verified CREATE SCHEMA permissions in the sample checked.')
print('')
print('π‘ This means you need CREATE SCHEMA permission on a catalog. Options:')
print(' 1. Ask your workspace admin to grant CREATE SCHEMA permission')
print(' 2. Use a catalog where you already have permissions')
print(' 3. Create your own catalog (if you have CREATE CATALOG permission)')
print('')
# Allow manual entry as fallback
while True:
try:
manual_catalog = input('Enter catalog name manually (or press Enter to skip): ').strip()
if not manual_catalog:
return None
# Test the manually entered catalog with CREATE SCHEMA verification
print(f"π Verifying CREATE SCHEMA permission on '{manual_catalog}'...")
try:
# First check if we can list schemas (USE CATALOG)
list(self.client.schemas.list(catalog_name=manual_catalog))
print(f"β
Can list schemas in '{manual_catalog}' - USE CATALOG confirmed")
# Then test CREATE SCHEMA permission
if self._test_create_schema_permission(manual_catalog):
print(f"β
CREATE SCHEMA permission verified on '{manual_catalog}'")
return manual_catalog
else:
print(f"β No CREATE SCHEMA permission on '{manual_catalog}'")
print(' You need CREATE SCHEMA permission to use this catalog')
continue
except Exception as e:
print(f"β Cannot access catalog '{manual_catalog}': {e}")
continue
except KeyboardInterrupt:
return None
print(
f'Available catalogs (showing {len(available_catalogs)} with VERIFIED '
f'CREATE SCHEMA permissions):'
)
catalog_list = list(available_catalogs.keys())
# Show suggested catalog first if it exists
if suggested_catalog and suggested_catalog in available_catalogs:
print(f' 0. {suggested_catalog} (suggested) - {available_catalogs[suggested_catalog]}')
start_idx = 1
else:
start_idx = 0
# Show other catalogs
for i, (catalog_name, access_level) in enumerate(available_catalogs.items()):
if catalog_name != suggested_catalog:
print(f' {start_idx + i}. {catalog_name} - {access_level}')
# Add option to manually enter catalog name
manual_entry_idx = len(catalog_list) + (1 if suggested_catalog in available_catalogs else 0)
print(f' {manual_entry_idx}. Enter catalog name manually')
max_choice = manual_entry_idx
while True:
try:
choice = input(f'\nSelect catalog (0-{max_choice}) or type catalog name: ').strip()
# Check if it's a number
try:
choice_num = int(choice)
if choice_num == 0 and suggested_catalog and suggested_catalog in available_catalogs:
return suggested_catalog
elif 1 <= choice_num <= len(catalog_list):
# Adjust index based on whether suggested catalog is shown
if suggested_catalog and suggested_catalog in available_catalogs:
selected_catalogs = [cat for cat in catalog_list if cat != suggested_catalog]
return selected_catalogs[choice_num - 1]
else:
return catalog_list[choice_num - 1]
elif choice_num == manual_entry_idx:
# Manual entry option
while True:
manual_catalog = input('Enter catalog name: ').strip()
if not manual_catalog:
print('β Catalog name cannot be empty')
continue
try:
list(self.client.schemas.list(catalog_name=manual_catalog))
print(f"β
Catalog '{manual_catalog}' is accessible")
return manual_catalog
except Exception as e:
print(f"β Cannot access catalog '{manual_catalog}': {e}")
continue
else:
print(f'β Please enter a number between 0 and {max_choice}')
continue
except ValueError:
# User typed a catalog name directly
if choice in available_catalogs:
return choice
else:
# Test the typed catalog name
try:
list(self.client.schemas.list(catalog_name=choice))
print(f"β
Catalog '{choice}' is accessible")
return choice
except Exception as e:
print(f"β Cannot access catalog '{choice}': {e}")
continue
except KeyboardInterrupt:
return None
def _prompt_for_schema_selection(self, catalog_name: str, suggested_schema: str = None) -> str:
"""Interactive schema selection with permission checking."""
print(f"\nπ Schema Selection in '{catalog_name}'")
# Get available schemas
available_schemas = self._get_available_schemas_in_catalog(catalog_name)
if not available_schemas:
print(f"No accessible schemas found in '{catalog_name}'. Will create new schema.")
new_schema = input('Enter new schema name [default]: ').strip()
return new_schema or 'default'
print('Available schemas:')
schema_list = list(available_schemas.keys())
# Show suggested schema first if it exists
if suggested_schema and suggested_schema in available_schemas:
print(f' 0. {suggested_schema} (suggested) - {available_schemas[suggested_schema]}')
start_idx = 1
else:
start_idx = 0
# Show other schemas
for i, (schema_name, access_level) in enumerate(available_schemas.items()):
if schema_name != suggested_schema:
print(f' {start_idx + i}. {schema_name} - {access_level}')
create_option_num = len(schema_list) + (1 if suggested_schema in available_schemas else 0)
print(f' {create_option_num}. Create new schema')
while True:
try:
max_choice = len(schema_list) + (1 if suggested_schema in available_schemas else 0)
choice = input(f'\nSelect schema (0-{max_choice}) or type schema name: ').strip()
# Check if it's a number
try:
choice_num = int(choice)
if choice_num == 0 and suggested_schema and suggested_schema in available_schemas:
return suggested_schema
elif 1 <= choice_num <= len(schema_list):
# Adjust index based on whether suggested schema is shown
if suggested_schema and suggested_schema in available_schemas:
selected_schemas = [sch for sch in schema_list if sch != suggested_schema]
return selected_schemas[choice_num - 1]
else:
return schema_list[choice_num - 1]
elif choice_num == len(schema_list) + (1 if suggested_schema in available_schemas else 0):
# Create new schema
new_schema = input('Enter new schema name: ').strip()
if new_schema:
print(f'π‘ Will create new schema: {new_schema}')
return new_schema
else:
max_choice = len(schema_list) + (1 if suggested_schema in available_schemas else 0)
print(f'β Please enter a number between 0 and {max_choice}')
continue
except ValueError:
# User typed a schema name directly
if choice in available_schemas:
return choice
else:
print(f'π‘ Will create new schema: {choice}')
return choice
except KeyboardInterrupt:
return None
def _validate_app_name(self, app_name: str) -> bool:
"""Validate app name format for Databricks Apps."""
import re
if not app_name:
return False
# App name must contain only lowercase letters, numbers, and dashes
pattern = r'^[a-z0-9-]+$'
return bool(re.match(pattern, app_name))
def _get_available_chat_models(self) -> List[str]:
"""Get list of available chat completion models from Databricks."""
try:
# Use the model discovery logic to find chat models
spinner = Spinner('Discovering available chat models...')
spinner.start()
try:
endpoints = self.client.serving_endpoints.list()
spinner.stop('Found serving endpoints')
except Exception as e:
spinner.stop()
raise e
# Common chat model patterns
chat_model_patterns = [
'gpt-',
'claude-',
'gemini-',
'llama',
'mistral',
'databricks-',
'chat',
'instruct',
'turbo',
]
potential_chat_models = []
for endpoint in endpoints:
model_name = endpoint.name.lower()
# Check if it matches chat patterns
is_likely_chat = any(pattern in model_name for pattern in chat_model_patterns)
# Exclude obvious non-chat models
is_not_chat = any(
exclude in model_name
for exclude in ['embedding', 'vision', 'audio', 'whisper', 'imageai']
)
if is_likely_chat and not is_not_chat:
# Check if endpoint has chat task capability
try:
endpoint_details = self.client.serving_endpoints.get(name=endpoint.name)
if hasattr(endpoint_details, 'config') and endpoint_details.config:
# Check served entities for task type
if (
hasattr(endpoint_details.config, 'served_entities')
and endpoint_details.config.served_entities
):
for entity in endpoint_details.config.served_entities:
if (
hasattr(entity, 'external_model')
and entity.external_model
and hasattr(entity.external_model, 'task')
and entity.external_model.task == 'llm/v1/chat'
):
potential_chat_models.append(endpoint.name)
break
elif (
hasattr(entity, 'foundation_model')
and entity.foundation_model
and hasattr(entity.foundation_model, 'name')
):
# Foundation models typically support chat
potential_chat_models.append(endpoint.name)
break
except Exception:
# If we can't get details, include it based on name pattern
potential_chat_models.append(endpoint.name)
# Remove duplicates and sort
chat_models = sorted(list(set(potential_chat_models)))
# Prioritize certain models at the top
priority_models = ['databricks-claude-3-7-sonnet', 'databricks-claude-sonnet-4', 'gpt-4o']
prioritized_models = []
for priority in priority_models:
if priority in chat_models:
prioritized_models.append(priority)
chat_models.remove(priority)
return prioritized_models + chat_models
except Exception as e:
print(f'β οΈ Could not discover chat models: {e}')
# Return default options
return [
'databricks-claude-3-7-sonnet',
'databricks-claude-sonnet-4',
'databricks-meta-llama-3-3-70b-instruct',
'gpt-4o',
]
def _prompt_for_deployment_mode(self) -> str:
"""Interactive deployment mode selection."""
print('\nπ Choose Your Interface')
print('')
print('Both options include the complete MLflow evaluation setup:')
print(
'β’ MLflow Experiment with sample traces, evaluation runs, prompts, and production monitoring'
)
print('β’ Sales email generation code with sample data')
print('β’ Interactive Notebooks that walk you through using MLflow to improve GenAI quality')
print('')
print('Choose how you want to interact with the demo:')
print('')
print(' 1. π± Databricks App (Recommended if Databricks Apps are enabled in your workspace)')
print(' β’ Adds a user-friendly web UI for exploring the workflows')
print(' β’ Interactive demo UI to try the sample app')
print(' β’ Include all the notebooks for deeper exploration')
print('')
print(' 2. π Notebooks Only')
print(" β’ Best option if you can't deploy Databricks Apps in your workspace")
print(' β’ Use the notebooks to understand how MLflow helps you improve GenAI quality')
print('')
while True:
try:
choice = input('Select experience (1 or 2) [default: 1]: ').strip()
# Default to full app deployment
if not choice:
choice = '1'
if choice == '1':
print('β
Selected: Full App Deployment')
return 'full_deployment'
elif choice == '2':
print('β
Selected: Notebook-Only Experience')
return 'notebook_only'
else:
print('β Please enter 1 or 2')
continue
except KeyboardInterrupt:
return 'notebook_only'
def _prompt_for_llm_model(self, suggested_model: str = None) -> str:
"""Interactive LLM model selection with available chat models."""
print('\nπ€ LLM Model Selection')
# Get available chat models
available_models = self._get_available_chat_models()
if not available_models:
print('β No chat models found. Using default.')
return suggested_model or 'databricks-claude-3-7-sonnet'
print('Available chat completion models:')
# Show suggested model first if it exists
if suggested_model and suggested_model in available_models:
print(f' 0. {suggested_model} (suggested)')
start_idx = 1
else:
start_idx = 0
# Show other models
for i, model_name in enumerate(available_models):
if model_name != suggested_model:
print(f' {start_idx + i}. {model_name}')
max_choice = len(available_models) - 1 + (1 if suggested_model in available_models else 0)
while True:
try:
choice = input(f'\nSelect model (0-{max_choice}) or press ENTER for default: ').strip()
# Use default if empty
if not choice:
return suggested_model or available_models[0]
# Check if it's a number
try:
choice_num = int(choice)
if choice_num == 0 and suggested_model and suggested_model in available_models:
return suggested_model
elif 1 <= choice_num <= len(available_models):
# Adjust index based on whether suggested model is shown
if suggested_model and suggested_model in available_models:
selected_models = [model for model in available_models if model != suggested_model]
return selected_models[choice_num - 1]
else:
return available_models[choice_num - 1]
else:
print(f'β Please enter a number between 0 and {max_choice}')
continue
except ValueError:
# User typed a model name directly
if choice in available_models:
return choice
else:
print(f"β Model '{choice}' not found in available models")
continue
except KeyboardInterrupt:
return suggested_model or available_models[0]
def _generate_default_app_name(self) -> str:
"""Generate a default app name with 4 random characters."""
import os
# Generate 4 random hex characters
random_chars = os.urandom(2).hex() # 2 bytes = 4 hex chars
return f'mlflow-demo-app-{random_chars}'
def _prompt_for_app_name(self, suggested_app_name: str = None) -> str:
"""Interactive app name selection with default suggestion."""
print('\nπ± Databricks App Name Selection')
# Generate a default name if no suggestion provided
if not suggested_app_name:
suggested_app_name = self._generate_default_app_name()
while True:
app_name = input(f'App name [{suggested_app_name}]: ').strip()
if not app_name:
app_name = suggested_app_name
if not self._validate_app_name(app_name):
print('β App name must contain only lowercase letters, numbers, and dashes')
continue
print(f'π‘ Will create app: {app_name}')
return app_name
def _restore_config_from_progress(self):
"""Restore configuration from saved progress."""
try:
# Look for saved config in completed steps
completed_step_ids = self.progress.get_completed_steps()
for step_id in completed_step_ids:
step_data = self.progress.steps.get(step_id)
if step_data and hasattr(step_data, 'result_data') and step_data.result_data:
if 'config' in step_data.result_data:
saved_config = step_data.result_data['config']
self.config.update(saved_config)
print(f'π Restored configuration from progress: {list(saved_config.keys())}')
# Also restore experiment ID if available
if 'experiment_id' in step_data.result_data:
self.config['MLFLOW_EXPERIMENT_ID'] = step_data.result_data['experiment_id']
print(f'π Restored experiment ID: {step_data.result_data["experiment_id"]}')
# Restore other important config values
if 'app_name' in step_data.result_data:
self.config['DATABRICKS_APP_NAME'] = step_data.result_data['app_name']
except Exception as e:
print(f'β οΈ Could not restore config from progress: {e}')
def _load_config_from_env_file(self):
"""Load configuration from .env.local file."""
try:
env_file = self.project_root / '.env.local'
if env_file.exists():
# Load environment variables from .env.local
load_dotenv(env_file)
# Update self.config with values from environment
env_mappings = {
'DATABRICKS_HOST': 'DATABRICKS_HOST',
'UC_CATALOG': 'UC_CATALOG',
'UC_SCHEMA': 'UC_SCHEMA',
'DATABRICKS_APP_NAME': 'DATABRICKS_APP_NAME',
'LLM_MODEL': 'LLM_MODEL',
'DEPLOYMENT_MODE': 'DEPLOYMENT_MODE',
'MLFLOW_EXPERIMENT_ID': 'MLFLOW_EXPERIMENT_ID',
'LHA_SOURCE_CODE_PATH': 'LHA_SOURCE_CODE_PATH',
}
loaded_keys = []
for config_key, env_key in env_mappings.items():
value = os.getenv(env_key)
if value:
self.config[config_key] = value
loaded_keys.append(config_key)
if loaded_keys:
print(f'π Loaded configuration from .env.local: {loaded_keys}')
else:
print('β οΈ .env.local file not found')
except Exception as e:
print(f'β οΈ Could not load config from .env.local: {e}')
def run_setup(self, resume: bool = False) -> bool:
"""Run the complete setup process.
Args:
resume: If True, resume from previous progress
Returns:
True if setup completed successfully
"""
print('π MLflow Demo Automated Setup')
print('=' * 50)
if not resume:
print(f'π§ Setup mode: {"DRY RUN" if self.dry_run else "LIVE"}')
else:
print('π Resuming previous setup...')
self.progress.show_detailed_progress()
# Restore configuration from previous progress if resuming
if resume:
self._restore_config_from_progress()
# Also load configuration from .env.local to ensure all values are present
self._load_config_from_env_file()
# Initialize Databricks components (skip auth prompts on resume if already working)
if not self._initialize_databricks_components(skip_auth_prompts=resume):
return False
try:
success = True
# Execute setup steps in order
while True:
next_step = self.progress.get_next_step()
if not next_step:
break
if not self.progress.start_step(next_step):
continue
try:
# Check if we should skip app-related steps for notebook-only mode
deployment_mode = self.config.get('DEPLOYMENT_MODE', 'full_deployment')
app_steps = [
'create_app',
'setup_permissions',
'validate_deployment',
'run_integration_tests',
]
if deployment_mode == 'notebook_only' and next_step in app_steps:
print(f'π Skipping {next_step} for notebook-only mode')
success = True # Skip successfully
elif next_step == 'validate_prerequisites':
success = self._validate_prerequisites()
elif next_step == 'detect_environment':
success = self._detect_environment()
elif next_step == 'collect_user_input':
success = self._collect_user_input()
elif next_step == 'validate_config':
success = self._validate_config()
elif next_step == 'show_installation_preview':
success = self._show_installation_preview()
elif next_step == 'create_catalog_schema':
success = self._create_catalog_schema()
elif next_step == 'create_experiment':
success = self._create_experiment()
elif next_step == 'create_app':
success = self._create_app()
elif next_step == 'setup_permissions':
success = self._setup_permissions()
elif next_step == 'generate_env_file':
success = self._generate_env_file()
elif next_step == 'install_dependencies':
success = self._install_dependencies()
elif next_step == 'load_sample_data':
success = self._load_sample_data()
elif next_step == 'validate_local_setup':
success = self._validate_local_setup()
elif next_step == 'deploy_app':
success = self._deploy_app()
elif next_step == 'validate_deployment':
success = self._validate_deployment()
elif next_step == 'run_integration_tests':
success = self._run_integration_tests()
else:
success = False
raise ValueError(f'Unknown step: {next_step}')
if success:
self.progress.complete_step(next_step, self._get_step_result(next_step))
else:
self.progress.fail_step(next_step, 'Step execution failed')
break
except Exception as e:
error_msg = f'Error in step {next_step}: {str(e)}'
print(f'β {error_msg}')
self.progress.fail_step(next_step, error_msg)
success = False
break
# Show final results
self._show_final_results(success)
return success
except KeyboardInterrupt:
print('\nβ οΈ Setup interrupted by user')
self._show_final_results(False)
return False
except Exception as e:
print(f'\nβ Unexpected error during setup: {e}')
self._show_final_results(False)
return False
def _validate_prerequisites(self) -> bool:
"""Validate prerequisites before setup."""
print('π Validating prerequisites...')
if self.dry_run:
print(' [DRY RUN] Would validate prerequisites')
return True
valid, issues = self.validator.validate_prerequisites()
if not valid:
print('β Prerequisites validation failed:')
for issue in issues:
print(f' β’ {issue}')
return False
return True
def _detect_environment(self) -> bool:
"""Detect environment settings."""
print('π Detecting environment settings...')
if self.dry_run:
print(' [DRY RUN] Would detect environment settings')
# Set dummy values for dry run
self.detected_settings = {
'workspace_url': 'https://demo.cloud.databricks.com',
'suggested_catalog': 'workspace',
'suggested_schema': 'default',
}
return True
# Detect workspace URL
workspace_url = self.env_detector.detect_workspace_url()
# Suggest catalog/schema
catalog, schema = self.env_detector.suggest_catalog_schema()
# Store detected settings
self.detected_settings = {
'workspace_url': workspace_url,
'suggested_catalog': catalog,
'suggested_schema': schema,
}
return True
def _collect_user_input(self) -> bool:
"""Collect required user input."""
print('π Collecting configuration...')
if self.dry_run:
print(' [DRY RUN] Would collect user input')
# Use dummy values for dry run
self.config = {
'DATABRICKS_HOST': 'https://demo.cloud.databricks.com',
'UC_CATALOG': 'workspace',
'UC_SCHEMA': 'default',
'DATABRICKS_APP_NAME': 'mlflow_demo_app',
'MLFLOW_EXPERIMENT_ID': '123456789',
'DEPLOYMENT_MODE': 'notebook_only', # Default to notebook-only for dry run
}
return True
print('\nπ Configuration Setup')
print('Please provide the following information:')
print('(Press Enter to use suggested values where available)\n')
# Get workspace URL automatically from the authenticated profile
workspace_url = self.detected_settings.get('workspace_url')
if not workspace_url:
try:
workspace_url = self.client.config.host
except Exception:
workspace_url = 'https://unknown-workspace.cloud.databricks.com'
print(f'β
Using workspace URL from profile: {workspace_url}')
# Choose deployment mode first
deployment_mode = self._prompt_for_deployment_mode()