-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.go
More file actions
407 lines (346 loc) · 9.73 KB
/
worker.go
File metadata and controls
407 lines (346 loc) · 9.73 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
package ml
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
coreio "dappco.re/go/core/io"
coreerr "dappco.re/go/core/log"
)
// WorkerConfig holds the worker's runtime configuration.
type WorkerConfig struct {
APIBase string
WorkerID string
Name string
APIKey string
GPUType string
VRAMGb int
Languages []string
Models []string
InferURL string
TaskType string
BatchSize int
PollInterval time.Duration
OneShot bool
DryRun bool
}
// APITask represents a task from the LEM API.
type APITask struct {
ID int `json:"id"`
TaskType string `json:"task_type"`
Status string `json:"status"`
Language string `json:"language"`
Domain string `json:"domain"`
ModelName string `json:"model_name"`
PromptID string `json:"prompt_id"`
PromptText string `json:"prompt_text"`
Config *struct {
Temperature float64 `json:"temperature,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
} `json:"config"`
Priority int `json:"priority"`
}
// RunWorkerLoop is the main worker loop that polls for tasks and processes them.
func RunWorkerLoop(cfg *WorkerConfig) {
log.Printf("LEM Worker starting")
log.Printf(" ID: %s", cfg.WorkerID)
log.Printf(" Name: %s", cfg.Name)
log.Printf(" API: %s", cfg.APIBase)
log.Printf(" Infer: %s", cfg.InferURL)
log.Printf(" GPU: %s (%d GB)", cfg.GPUType, cfg.VRAMGb)
log.Printf(" Langs: %v", cfg.Languages)
log.Printf(" Models: %v", cfg.Models)
log.Printf(" Batch: %d", cfg.BatchSize)
log.Printf(" Dry-run: %v", cfg.DryRun)
if err := workerRegister(cfg); err != nil {
log.Fatalf("Registration failed: %v", err)
}
log.Println("Registered with LEM API")
for {
processed := workerPoll(cfg)
if cfg.OneShot {
log.Printf("One-shot mode: processed %d tasks, exiting", processed)
return
}
if processed == 0 {
log.Printf("No tasks available, sleeping %v", cfg.PollInterval)
time.Sleep(cfg.PollInterval)
}
workerHeartbeat(cfg)
}
}
func workerRegister(cfg *WorkerConfig) error {
body := map[string]any{
"worker_id": cfg.WorkerID,
"name": cfg.Name,
"version": "0.1.0",
"os": runtime.GOOS,
"arch": runtime.GOARCH,
}
if cfg.GPUType != "" {
body["gpu_type"] = cfg.GPUType
}
if cfg.VRAMGb > 0 {
body["vram_gb"] = cfg.VRAMGb
}
if len(cfg.Languages) > 0 {
body["languages"] = cfg.Languages
}
if len(cfg.Models) > 0 {
body["supported_models"] = cfg.Models
}
_, err := apiPost(cfg, "/api/lem/workers/register", body)
return err
}
func workerHeartbeat(cfg *WorkerConfig) {
body := map[string]any{
"worker_id": cfg.WorkerID,
}
apiPost(cfg, "/api/lem/workers/heartbeat", body)
}
func workerPoll(cfg *WorkerConfig) int {
url := fmt.Sprintf("/api/lem/tasks/next?worker_id=%s&limit=%d", cfg.WorkerID, cfg.BatchSize)
if cfg.TaskType != "" {
url += "&type=" + cfg.TaskType
}
resp, err := apiGet(cfg, url)
if err != nil {
log.Printf("Error fetching tasks: %v", err)
return 0
}
var result struct {
Tasks []APITask `json:"tasks"`
Count int `json:"count"`
}
if err := json.Unmarshal(resp, &result); err != nil {
log.Printf("Error parsing tasks: %v", err)
return 0
}
if result.Count == 0 {
return 0
}
log.Printf("Got %d tasks", result.Count)
processed := 0
for _, task := range result.Tasks {
if err := workerProcessTask(cfg, task); err != nil {
log.Printf("Task %d failed: %v", task.ID, err)
apiDelete(cfg, fmt.Sprintf("/api/lem/tasks/%d/claim", task.ID), map[string]any{
"worker_id": cfg.WorkerID,
})
continue
}
processed++
}
return processed
}
func workerProcessTask(cfg *WorkerConfig, task APITask) error {
log.Printf("Processing task %d: %s [%s/%s] %d chars prompt",
task.ID, task.TaskType, task.Language, task.Domain, len(task.PromptText))
_, err := apiPost(cfg, fmt.Sprintf("/api/lem/tasks/%d/claim", task.ID), map[string]any{
"worker_id": cfg.WorkerID,
})
if err != nil {
return coreerr.E("ml.workerProcessTask", "claim", err)
}
apiPatch(cfg, fmt.Sprintf("/api/lem/tasks/%d/status", task.ID), map[string]any{
"worker_id": cfg.WorkerID,
"status": "in_progress",
})
if cfg.DryRun {
log.Printf(" [DRY-RUN] Would generate response for: %.80s...", task.PromptText)
return nil
}
start := time.Now()
response, err := workerInfer(cfg, task)
genTime := time.Since(start)
if err != nil {
apiPatch(cfg, fmt.Sprintf("/api/lem/tasks/%d/status", task.ID), map[string]any{
"worker_id": cfg.WorkerID,
"status": "abandoned",
})
return coreerr.E("ml.workerProcessTask", "inference", err)
}
modelUsed := task.ModelName
if modelUsed == "" {
modelUsed = "default"
}
_, err = apiPost(cfg, fmt.Sprintf("/api/lem/tasks/%d/result", task.ID), map[string]any{
"worker_id": cfg.WorkerID,
"response_text": response,
"model_used": modelUsed,
"gen_time_ms": int(genTime.Milliseconds()),
})
if err != nil {
return coreerr.E("ml.workerProcessTask", "submit result", err)
}
log.Printf(" Completed: %d chars in %v", len(response), genTime.Round(time.Millisecond))
return nil
}
func workerInfer(cfg *WorkerConfig, task APITask) (string, error) {
messages := []map[string]string{
{"role": "user", "content": task.PromptText},
}
temp := 0.7
maxTokens := 2048
if task.Config != nil {
if task.Config.Temperature > 0 {
temp = task.Config.Temperature
}
if task.Config.MaxTokens > 0 {
maxTokens = task.Config.MaxTokens
}
}
reqBody := map[string]any{
"model": task.ModelName,
"messages": messages,
"temperature": temp,
"max_tokens": maxTokens,
}
data, err := json.Marshal(reqBody)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", cfg.InferURL+"/v1/chat/completions", bytes.NewReader(data))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 5 * time.Minute}
resp, err := client.Do(req)
if err != nil {
return "", coreerr.E("ml.workerInfer", "inference request", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", coreerr.E("ml.workerInfer", "read response", err)
}
if resp.StatusCode != 200 {
return "", coreerr.E("ml.workerInfer", fmt.Sprintf("inference HTTP %d: %s", resp.StatusCode, truncStr(string(body), 200)), nil)
}
var chatResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(body, &chatResp); err != nil {
return "", coreerr.E("ml.workerInfer", "parse response", err)
}
if len(chatResp.Choices) == 0 {
return "", coreerr.E("ml.workerInfer", "no choices in response", nil)
}
content := chatResp.Choices[0].Message.Content
if len(content) < 10 {
return "", coreerr.E("ml.workerInfer", fmt.Sprintf("response too short: %d chars", len(content)), nil)
}
return content, nil
}
// HTTP helpers for the LEM API.
func apiGet(cfg *WorkerConfig, path string) ([]byte, error) {
req, err := http.NewRequest("GET", cfg.APIBase+path, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+cfg.APIKey)
client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
return nil, coreerr.E("ml.apiGet", fmt.Sprintf("HTTP %d: %s", resp.StatusCode, truncStr(string(body), 200)), nil)
}
return body, nil
}
func apiPost(cfg *WorkerConfig, path string, data map[string]any) ([]byte, error) {
return apiRequest(cfg, "POST", path, data)
}
func apiPatch(cfg *WorkerConfig, path string, data map[string]any) ([]byte, error) {
return apiRequest(cfg, "PATCH", path, data)
}
func apiDelete(cfg *WorkerConfig, path string, data map[string]any) ([]byte, error) {
return apiRequest(cfg, "DELETE", path, data)
}
func apiRequest(cfg *WorkerConfig, method, path string, data map[string]any) ([]byte, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, cfg.APIBase+path, bytes.NewReader(jsonData))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+cfg.APIKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
return nil, coreerr.E("ml.apiRequest", fmt.Sprintf("HTTP %d: %s", resp.StatusCode, truncStr(string(body), 200)), nil)
}
return body, nil
}
// MachineID returns the machine ID from /etc/machine-id or hostname fallback.
func MachineID() string {
if data, err := coreio.Local.Read("/etc/machine-id"); err == nil {
id := strings.TrimSpace(data)
if len(id) > 0 {
return id
}
}
h, _ := os.Hostname()
return h
}
// Hostname returns the system hostname.
func Hostname() string {
h, _ := os.Hostname()
return h
}
// ReadKeyFile reads the LEM API key from ~/.config/lem/api_key.
func ReadKeyFile() string {
home, _ := os.UserHomeDir()
path := filepath.Join(home, ".config", "lem", "api_key")
data, err := coreio.Local.Read(path)
if err != nil {
return ""
}
return strings.TrimSpace(data)
}
// SplitComma splits a comma-separated string into trimmed parts.
func SplitComma(s string) []string {
var result []string
for part := range bytes.SplitSeq([]byte(s), []byte(",")) {
trimmed := bytes.TrimSpace(part)
if len(trimmed) > 0 {
result = append(result, string(trimmed))
}
}
return result
}
func truncStr(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "..."
}