ciyidogan commited on
Commit
4f5da3c
·
verified ·
1 Parent(s): b340d79

Rename spark_startup.py to llm_startup.py

Browse files
Files changed (2) hide show
  1. llm_startup.py +102 -0
  2. spark_startup.py +0 -106
llm_startup.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Flare – LLM startup notifier (Refactored)
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+ Projeler açılırken LLM provider'a startup çağrısı yapar.
5
+ """
6
+
7
+ from __future__ import annotations
8
+ import threading
9
+ import asyncio
10
+ from typing import Dict, Any
11
+ from utils import log
12
+ from config_provider import ConfigProvider, ProjectConfig, VersionConfig
13
+ from llm_factory import LLMFactory
14
+
15
+ def _select_live_version(p: ProjectConfig) -> VersionConfig | None:
16
+ """Yayınlanmış en güncel versiyonu getir."""
17
+ published = [v for v in p.versions if v.published]
18
+ return max(published, key=lambda v: v.id) if published else None
19
+
20
+ async def notify_startup_async():
21
+ """Notify LLM provider about project startups (async version)"""
22
+ cfg = ConfigProvider.get()
23
+
24
+ # Check if LLM provider requires repo info
25
+ llm_provider_def = cfg.global_config.get_provider_config(
26
+ "llm",
27
+ cfg.global_config.llm_provider.name
28
+ )
29
+
30
+ if not llm_provider_def or not llm_provider_def.requires_repo_info:
31
+ log(f"ℹ️ LLM provider '{cfg.global_config.llm_provider.name}' does not require startup notification")
32
+ return
33
+
34
+ # Create LLM provider instance
35
+ try:
36
+ llm_provider = LLMFactory.create_provider()
37
+ except Exception as e:
38
+ log(f"❌ Failed to create LLM provider for startup: {e}")
39
+ return
40
+
41
+ # Notify for each enabled project
42
+ enabled_projects = [p for p in cfg.projects if p.enabled and not getattr(p, 'deleted', False)]
43
+
44
+ if not enabled_projects:
45
+ log("ℹ️ No enabled projects found for startup notification")
46
+ return
47
+
48
+ for project in enabled_projects:
49
+ version = _select_live_version(project)
50
+ if not version:
51
+ log(f"⚠️ No published version found for project '{project.name}', skipping startup")
52
+ continue
53
+
54
+ # Build project config
55
+ project_config = {
56
+ "name": project.name,
57
+ "version_id": version.id,
58
+ "repo_id": version.llm.repo_id,
59
+ "generation_config": version.llm.generation_config,
60
+ "use_fine_tune": version.llm.use_fine_tune,
61
+ "fine_tune_zip": version.llm.fine_tune_zip
62
+ }
63
+
64
+ try:
65
+ log(f"🚀 Notifying LLM provider startup for project '{project.name}'...")
66
+ success = await llm_provider.startup(project_config)
67
+
68
+ if success:
69
+ log(f"✅ LLM provider acknowledged startup for '{project.name}'")
70
+ else:
71
+ log(f"⚠️ LLM provider startup failed for '{project.name}'")
72
+
73
+ except Exception as e:
74
+ log(f"❌ Error during startup notification for '{project.name}': {e}")
75
+
76
+ def notify_startup():
77
+ """Synchronous wrapper for async startup notification"""
78
+ # Create new event loop for thread
79
+ loop = asyncio.new_event_loop()
80
+ asyncio.set_event_loop(loop)
81
+
82
+ try:
83
+ loop.run_until_complete(notify_startup_async())
84
+ finally:
85
+ loop.close()
86
+
87
+ def run_in_thread():
88
+ """Start startup notification in background thread"""
89
+ cfg = ConfigProvider.get()
90
+
91
+ # Check if provider requires startup
92
+ llm_provider_def = cfg.global_config.get_provider_config(
93
+ "llm",
94
+ cfg.global_config.llm_provider.name
95
+ )
96
+
97
+ if not llm_provider_def or not llm_provider_def.requires_repo_info:
98
+ log(f"🤖 {cfg.global_config.llm_provider.name} - Startup notification not required")
99
+ return
100
+
101
+ log("🚀 Starting LLM provider startup notification thread...")
102
+ threading.Thread(target=notify_startup, daemon=True).start()
spark_startup.py DELETED
@@ -1,106 +0,0 @@
1
- """
2
- Flare – LLM startup notifier
3
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
- Projeler açılırken LLM provider'a startup çağrısı yapar.
5
- """
6
-
7
- from __future__ import annotations
8
- import threading, requests, os
9
- from typing import Dict, Any
10
- from utils import log
11
- from config_provider import ConfigProvider, ProjectConfig, VersionConfig
12
- from llm_factory import LLMFactory
13
-
14
- def _select_live_version(p: ProjectConfig) -> VersionConfig | None:
15
- """Yayınlanmış en güncel versiyonu getir."""
16
- published = [v for v in p.versions if v.published]
17
- return max(published, key=lambda v: v.id) if published else None
18
-
19
- def notify_startup():
20
- """Notify LLM provider about project startups"""
21
- cfg = ConfigProvider.get()
22
-
23
- # Check if current provider needs startup notification
24
- llm_config = cfg.global_config.llm_provider
25
- if not llm_config:
26
- log("⚠️ No LLM provider configured")
27
- return
28
-
29
- provider_def = cfg.global_config.get_provider_config("llm", llm_config.name)
30
- if not provider_def:
31
- log(f"⚠️ Unknown LLM provider: {llm_config.name}")
32
- return
33
-
34
- # Currently only Spark variants need startup
35
- if llm_config.name not in ("spark", "spark_cloud", "spark_onpremise"):
36
- log(f"ℹ️ {llm_config.name} doesn't require startup notification")
37
- return
38
-
39
- # Check if provider requires repo info
40
- if not provider_def.requires_repo_info:
41
- log(f"ℹ️ {llm_config.name} doesn't require repo info for startup")
42
- return
43
-
44
- # Get endpoint and API key
45
- endpoint = llm_config.endpoint
46
- if not endpoint:
47
- log("⚠️ No LLM endpoint configured for startup")
48
- return
49
-
50
- api_key = cfg.global_config.get_plain_api_key("llm")
51
- if not api_key:
52
- # Try environment
53
- env_var = "SPARK_TOKEN"
54
- if os.environ.get("SPACE_ID"):
55
- api_key = os.environ.get(env_var)
56
- else:
57
- from dotenv import load_dotenv
58
- load_dotenv()
59
- api_key = os.getenv(env_var)
60
-
61
- if not api_key:
62
- log("⚠️ No API key available for startup")
63
- return
64
-
65
- spark_base = str(endpoint).rstrip("/")
66
-
67
- for p in cfg.projects:
68
- if not p.enabled:
69
- continue
70
- v = _select_live_version(p)
71
- if not v:
72
- continue
73
-
74
- # Check if version has LLM config (required for Spark)
75
- if not v.llm:
76
- log(f"⚠️ No LLM config in version {v.id} for project '{p.name}'")
77
- continue
78
-
79
- body: Dict[str, Any] = {
80
- # Required fields for Spark startup
81
- "project_name": p.name,
82
- "project_version": v.id,
83
- "repo_id": v.llm.repo_id,
84
- "generation_config": v.llm.generation_config,
85
- "use_fine_tune": v.llm.use_fine_tune,
86
- "fine_tune_zip": v.llm.fine_tune_zip,
87
- }
88
-
89
- headers = {
90
- "Authorization": f"Bearer {api_key}",
91
- "Content-Type": "application/json"
92
- }
93
-
94
- try:
95
- log(f"🚀 Notifying {llm_config.name} /startup for project '{p.name}' …")
96
- r = requests.post(f"{spark_base}/startup", json=body, headers=headers, timeout=10)
97
- if r.status_code >= 400:
98
- log(f"❌ LLM provider responded {r.status_code}: {r.text}")
99
- r.raise_for_status()
100
- log(f"✅ LLM provider acknowledged startup ({r.status_code})")
101
- except Exception as e:
102
- log(f"⚠️ LLM startup failed: {e}")
103
-
104
- def run_in_thread():
105
- """Run startup notification in background thread"""
106
- threading.Thread(target=notify_startup, daemon=True).start()