Adding Files From Github

#1
by studzinsky - opened
.gitignore DELETED
@@ -1,56 +0,0 @@
1
- # Byte-compiled / optimized / DLL files
2
- __pycache__/
3
- *.py[cod]
4
- *.pyo
5
- *.pyd
6
-
7
- # Virtual environment
8
- venv/
9
- env/
10
-
11
- # Model files and large data
12
- /app/pretrain_model/
13
- *.bin
14
- *.safetensors
15
- *.gguf
16
-
17
- # Secrets
18
- my_hf_token.txt
19
- /run/secrets/
20
-
21
- # Logs and debug files
22
- *.log
23
- *.out
24
- *.err
25
-
26
- # IDE and editor settings
27
- .vscode/
28
- .idea/
29
- *.swp
30
- *.swo
31
-
32
- # Docker
33
- *.env
34
- *.dockerignore
35
- docker-compose.override.yml
36
-
37
- # Python package files
38
- *.egg
39
- *.egg-info/
40
- dist/
41
- build/
42
- *.wheel
43
-
44
- # Cache files
45
- *.cache
46
- *.mypy_cache/
47
- *.pytest_cache/
48
- *.ipynb_checkpoints/
49
-
50
- # System files
51
- .DS_Store
52
- Thumbs.db
53
-
54
- # Gemini Plans
55
- gemini_plans/
56
- llm_app_rework.md
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile DELETED
@@ -1,43 +0,0 @@
1
- # GPU-enabled Dockerfile (works on both GPU and CPU hardware)
2
- # Uses NVIDIA CUDA base image for optimal performance on GPU
3
- # Falls back gracefully to CPU if GPU not available
4
- FROM nvidia/cuda:12.1.1-runtime-ubuntu22.04
5
-
6
- WORKDIR /app
7
-
8
- ENV MODEL_DIR=/app/pretrain_model
9
- ENV HF_HUB_DISABLE_SYMLINKS_WARNING=1
10
- ENV HF_TOKEN=""
11
- ENV PYTHONUNBUFFERED=1
12
-
13
- # Install Python 3.10 and build tools
14
- RUN apt-get update && apt-get install -y \
15
- python3.10 \
16
- python3-pip \
17
- build-essential \
18
- cmake \
19
- pkg-config \
20
- curl \
21
- git \
22
- && rm -rf /var/lib/apt/lists/*
23
-
24
- # Set python3.10 as default
25
- RUN ln -sf /usr/bin/python3.10 /usr/bin/python && ln -sf /usr/bin/python3.10 /usr/bin/python3
26
-
27
- COPY requirements.txt .
28
-
29
- RUN pip install --no-cache-dir --upgrade pip && \
30
- pip install --no-cache-dir -r requirements.txt
31
-
32
- # Note: llama-cpp-python will be installed at runtime (see app/main.py)
33
- # This avoids long build times and complex CUDA setup during build
34
-
35
- # Model downloads are deferred to first request to speed up build time
36
- # They will be downloaded on first API call via app/models/registry.py
37
- # This makes builds fast while still pre-caching models on subsequent deployments
38
-
39
- COPY . .
40
-
41
- EXPOSE 8000
42
-
43
- CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,426 +1,12 @@
1
  ---
2
  title: Bielik App Service
3
- emoji: 🤖
4
- colorFrom: blue
5
- colorTo: purple
6
  sdk: docker
7
- app_port: 7860
8
  pinned: false
 
 
9
  ---
10
 
11
- # Bielik App Service
12
-
13
- Multi-model LLM service for description enhancement, batch gap-filling, and A/B testing.
14
-
15
- ## Overview
16
-
17
- This service provides an API for generating enhanced descriptions using multiple open-source LLMs. It supports:
18
- - **Description Enhancement**: Generate marketing descriptions from structured data
19
- - **Batch Infill**: Fill gaps (`[GAP:n]` or `___`) in ad texts with natural words
20
- - **Multi-Model Comparison**: Compare outputs across different models for A/B testing
21
-
22
- ## Models
23
-
24
- | Model | Size | Polish Support | Type |
25
- |-------|------|----------------|------|
26
- | Bielik-1.5B | 1.5B | Excellent | Local |
27
- | Bielik-1.5B-GGUF | 1.5B | Excellent | Local (CPU Optimized) |
28
- | PLLuM-12B | 12B | Excellent | API |
29
-
30
- ## API Endpoints
31
-
32
- ### Health & Info
33
-
34
- | Method | Endpoint | Description |
35
- |--------|----------|-------------|
36
- | `GET` | `/` | Welcome message |
37
- | `GET` | `/health` | API health check and model status |
38
- | `GET` | `/models` | List all available models |
39
-
40
- ### Model Management (Lazy Loading)
41
-
42
- | Method | Endpoint | Description |
43
- |--------|----------|-------------|
44
- | `POST` | `/models/{name}/load` | Load a model into memory |
45
- | `POST` | `/models/{name}/unload` | Unload a model from memory |
46
-
47
- ### Description Generation
48
-
49
- | Method | Endpoint | Description |
50
- |--------|----------|-------------|
51
- | `POST` | `/enhance-description` | Generate description with single model |
52
- | `POST` | `/compare` | Compare outputs from multiple models |
53
-
54
- ### Batch Infill (Gap-Filling)
55
-
56
- | Method | Endpoint | Description |
57
- |--------|----------|-------------|
58
- | `POST` | `/infill` | Batch gap-filling with single model |
59
- | `POST` | `/compare-infill` | Compare gap-filling across multiple models |
60
-
61
- ---
62
-
63
- ## Lazy Loading
64
-
65
- Models are **not loaded at startup** to conserve memory. Instead:
66
- - Models are loaded **on first request** (lazy loading)
67
- - Only **one local model** is loaded at a time
68
- - Switching to a different local model **automatically unloads** the previous one
69
- - API models (PLLuM) don't affect local model memory
70
-
71
- ### Example: Load/Unload Flow
72
- ```
73
- 1. Request with bielik-1.5b → Loads Bielik (first use)
74
- 2. Request with bielik-1.5b-gguf → Unloads Bielik, loads GGUF
75
- 3. Request with pllum-12b → GGUF stays loaded (API model doesn't affect local)
76
- 4. POST /models/bielik-1.5b-gguf/unload → Manually free memory
77
- ```
78
-
79
- ---
80
-
81
- ## Endpoint Details
82
-
83
- ### `GET /health`
84
-
85
- Check API status and loaded models.
86
-
87
- **Response:**
88
- ```json
89
- {
90
- "status": "ok",
91
- "available_models": 4,
92
- "loaded_models": ["bielik-1.5b"],
93
- "active_local_model": "bielik-1.5b"
94
- }
95
- ```
96
-
97
- ---
98
-
99
- ### `GET /models`
100
-
101
- List all available models with their load status.
102
-
103
- **Response:**
104
- ```json
105
- [
106
- {
107
- "name": "bielik-1.5b",
108
- "model_id": "speakleash/Bielik-1.5B-v3.0-Instruct",
109
- "type": "local",
110
- "polish_support": "excellent",
111
- "size": "1.5B",
112
- "loaded": true,
113
- "active": true
114
- },
115
- {
116
- "name": "qwen2.5-3b",
117
- "model_id": "Qwen/Qwen2.5-3B-Instruct",
118
- "type": "local",
119
- "polish_support": "good",
120
- "size": "3B",
121
- "loaded": false,
122
- "active": false
123
- }
124
- ]
125
- ```
126
-
127
- ---
128
-
129
- ### `POST /models/{name}/load`
130
-
131
- Explicitly load a model. For local models, unloads the previous one first.
132
-
133
- **Response:**
134
- ```json
135
- {
136
- "status": "loaded",
137
- "model": {
138
- "name": "bielik-1.5b",
139
- "loaded": true,
140
- "active": true
141
- }
142
- }
143
- ```
144
-
145
- ---
146
-
147
- ### `POST /models/{name}/unload`
148
-
149
- Explicitly unload a model to free memory.
150
-
151
- **Response:**
152
- ```json
153
- {
154
- "status": "unloaded",
155
- "model": "bielik-1.5b"
156
- }
157
- ```
158
-
159
- ---
160
-
161
- ### `POST /enhance-description`
162
-
163
- Generate enhanced description using a single model.
164
-
165
- **Request:**
166
- ```json
167
- {
168
- "domain": "cars",
169
- "data": {
170
- "make": "BMW",
171
- "model": "320i",
172
- "year": 2020,
173
- "mileage": 45000,
174
- "features": ["nawigacja", "klimatyzacja"],
175
- "condition": "bardzo dobry"
176
- },
177
- "model": "bielik-1.5b"
178
- }
179
- ```
180
-
181
- **Response:**
182
- ```json
183
- {
184
- "description": "Generated description text...",
185
- "model_used": "speakleash/Bielik-1.5B-v3.0-Instruct",
186
- "generation_time": 2.34,
187
- "user_email": "anonymous"
188
- }
189
- ```
190
-
191
- ---
192
-
193
- ### `POST /compare`
194
-
195
- Compare outputs from multiple models for the same input.
196
-
197
- **Request:**
198
- ```json
199
- {
200
- "domain": "cars",
201
- "data": {
202
- "make": "BMW",
203
- "model": "320i",
204
- "year": 2020,
205
- "mileage": 45000,
206
- "features": ["nawigacja", "klimatyzacja"],
207
- "condition": "bardzo dobry"
208
- },
209
- "models": ["bielik-1.5b", "qwen2.5-3b", "gemma-2-2b", "pllum-12b"]
210
- }
211
- ```
212
-
213
- **Response:**
214
- ```json
215
- {
216
- "domain": "cars",
217
- "results": [
218
- {
219
- "model": "bielik-1.5b",
220
- "output": "Generated text from Bielik...",
221
- "time": 2.3,
222
- "type": "local",
223
- "error": null
224
- },
225
- {
226
- "model": "pllum-12b",
227
- "output": "Generated text from PLLuM...",
228
- "time": 1.1,
229
- "type": "inference_api",
230
- "error": null
231
- }
232
- ],
233
- "total_time": 5.67
234
- }
235
- ```
236
-
237
- ---
238
-
239
- ### `POST /infill`
240
-
241
- Batch gap-filling for ads using a single model. Accepts texts with `[GAP:n]` markers or `___` and returns filled text with per-gap choices and alternatives.
242
-
243
- **Gap Notation:**
244
- - `[GAP:1]`, `[GAP:2]`, ... → Explicit numbered gaps (preferred)
245
- - `___` → Auto-numbered in scan order
246
-
247
- **Request:**
248
- ```json
249
- {
250
- "domain": "cars",
251
- "items": [
252
- {
253
- "id": "ad1",
254
- "text_with_gaps": "Sprzedam [GAP:1] BMW w [GAP:2] stanie technicznym",
255
- "custom_messages": [
256
- {"role": "system", "content": "Custom system prompt..."},
257
- {"role": "user", "content": "Custom user prompt..."}
258
- ]
259
- },
260
- {
261
- "id": "ad2",
262
- "text_with_gaps": "Auto ma ___ km przebiegu i ___ lakier"
263
- }
264
- ],
265
- "model": "bielik-1.5b",
266
- "options": {
267
- "top_n_per_gap": 3,
268
- "language": "pl",
269
- "temperature": 0.6
270
- }
271
- }
272
- ```
273
- **Features:**
274
- - **Custom Messages:** Optional `custom_messages` field in items allows overriding the default prompt generation logic (e.g., for RAG integration).
275
-
276
- **Response:**
277
- ```json
278
- {
279
- "model": "bielik-1.5b",
280
- "results": [
281
- {
282
- "id": "ad1",
283
- "status": "ok",
284
- "filled_text": "Sprzedam eleganckie BMW w doskonałym stanie technicznym",
285
- "gaps": [
286
- {
287
- "index": 1,
288
- "marker": "[GAP:1]",
289
- "choice": "eleganckie",
290
- "alternatives": ["piękne", "zadbane"]
291
- },
292
- {
293
- "index": 2,
294
- "marker": "[GAP:2]",
295
- "choice": "doskonałym",
296
- "alternatives": ["bardzo dobrym", "idealnym"]
297
- }
298
- ],
299
- "error": null
300
- }
301
- ],
302
- "total_time": 3.45,
303
- "processed_count": 2,
304
- "error_count": 0
305
- }
306
- ```
307
-
308
- **Options:**
309
- | Field | Type | Default | Description |
310
- |-------|------|---------|-------------|
311
- | `gap_notation` | string | `"auto"` | `"auto"`, `"[GAP:n]"`, or `"___"` |
312
- | `top_n_per_gap` | int | `3` | Alternatives per gap (1-5) |
313
- | `language` | string | `"pl"` | Output language |
314
- | `temperature` | float | `0.6` | Generation temperature (0-1) |
315
- | `max_new_tokens` | int | `256` | Max tokens to generate |
316
-
317
- ---
318
-
319
- ### `POST /compare-infill`
320
-
321
- Multi-model batch gap-filling comparison for A/B testing.
322
-
323
- **Request:**
324
- ```json
325
- {
326
- "domain": "cars",
327
- "items": [
328
- {
329
- "id": "ad1",
330
- "text_with_gaps": "Sprzedam [GAP:1] BMW w [GAP:2] stanie"
331
- }
332
- ],
333
- "models": ["bielik-1.5b", "qwen2.5-3b", "pllum-12b"],
334
- "options": {
335
- "top_n_per_gap": 3
336
- }
337
- }
338
- ```
339
-
340
- **Response:**
341
- ```json
342
- {
343
- "domain": "cars",
344
- "models": [
345
- {
346
- "model": "bielik-1.5b",
347
- "type": "local",
348
- "results": [...],
349
- "time": 2.1,
350
- "error_count": 0
351
- },
352
- {
353
- "model": "qwen2.5-3b",
354
- "type": "local",
355
- "results": [...],
356
- "time": 1.8,
357
- "error_count": 0
358
- }
359
- ],
360
- "total_time": 5.2
361
- }
362
- ```
363
-
364
- ---
365
-
366
- ## Performance Improvements
367
-
368
- To optimize performance on CPU-only environments (like free Hugging Face Spaces):
369
-
370
- 1. **Dynamic Quantization:** Automatically applies `torch.quantization.quantize_dynamic` when running on CPU. This converts Linear layers to `int8`, reducing memory usage (~4x) and increasing inference speed (~2x) with minimal accuracy loss.
371
- 2. **Response Caching:** Implements an in-memory LRU cache for model generations. Identical requests (same prompt + parameters) return instantly from cache, which is ideal for testing and repeated queries.
372
- 3. **Lazy Loading:** Models are loaded only when requested and unloaded to free memory for other models.
373
-
374
- ## Domains
375
-
376
- Currently supported domains:
377
-
378
- | Domain | Schema Fields |
379
- |--------|---------------|
380
- | `cars` | `make`, `model`, `year`, `mileage`, `features[]`, `condition` |
381
-
382
- ---
383
-
384
- ## Environment Variables
385
-
386
- | Variable | Description | Required |
387
- |----------|-------------|----------|
388
- | `HF_TOKEN` | HuggingFace API token for Inference API | Yes (for API models) |
389
- | `LOCAL_MODEL_PATH` | Path to pre-downloaded local model | No (default: `/app/pretrain_model`) |
390
- | `FRONTEND_URL` | Frontend URL for CORS | No |
391
-
392
- ## Running Locally
393
-
394
- ```bash
395
- # Install dependencies
396
- pip install -r requirements.txt
397
-
398
- # Run server
399
- uvicorn app.main:app --reload --port 8000
400
- ```
401
-
402
- ## Docker
403
-
404
- ```bash
405
- # Build and run
406
- ./start_container.ps1
407
- ```
408
-
409
- API available at `http://localhost:8000`
410
-
411
- Docs at `http://localhost:8000/docs`
412
-
413
- ## Live Demo
414
-
415
- Deployed on HuggingFace Spaces:
416
-
417
- **URL:** `https://studzinsky-bielik-app-service.hf.space`
418
-
419
- **Quick Test:**
420
- ```bash
421
- # Health check
422
- curl https://studzinsky-bielik-app-service.hf.space/health
423
-
424
- # List models
425
- curl https://studzinsky-bielik-app-service.hf.space/models
426
- ```
 
1
  ---
2
  title: Bielik App Service
3
+ emoji: 🏃
4
+ colorFrom: yellow
5
+ colorTo: yellow
6
  sdk: docker
 
7
  pinned: false
8
+ license: mit
9
+ short_description: This is a description enhancer service running with bielik
10
  ---
11
 
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
VERSION DELETED
@@ -1 +0,0 @@
1
- 0.1.1
 
 
app/auth/__init__.py DELETED
@@ -1,7 +0,0 @@
1
- """
2
- Authentication module placeholder.
3
- """
4
-
5
- from .placeholder_auth import get_authenticated_user, get_optional_user
6
-
7
- __all__ = ["get_authenticated_user", "get_optional_user"]
 
 
 
 
 
 
 
 
app/auth/placeholder_auth.py DELETED
@@ -1,85 +0,0 @@
1
- """
2
- Simple token-based authentication module.
3
- Uses a secret API token stored as environment variable.
4
- """
5
-
6
- import os
7
- from typing import Optional
8
- from fastapi import Depends, HTTPException, status
9
- from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
10
-
11
- # Security scheme - auto_error=False allows unauthenticated requests to pass through
12
- security = HTTPBearer(auto_error=False)
13
-
14
- # Get API token from environment variable (set as HuggingFace secret)
15
- API_SECRET_TOKEN = os.getenv("API_SECRET_TOKEN", None)
16
-
17
-
18
- async def get_authenticated_user(
19
- credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
20
- ) -> dict:
21
- """
22
- Simple token-based authentication.
23
-
24
- If API_SECRET_TOKEN is set:
25
- - Requires valid Bearer token matching the secret
26
- If API_SECRET_TOKEN is not set:
27
- - Allows all requests (development mode)
28
-
29
- Usage:
30
- 1. Set API_SECRET_TOKEN as a HuggingFace Space secret
31
- 2. Send requests with header: Authorization: Bearer <your-token>
32
- """
33
-
34
- # If no secret is configured, allow all requests (dev mode)
35
- if not API_SECRET_TOKEN:
36
- return {
37
- "user_id": "anonymous",
38
- "email": "anonymous@example.com",
39
- "name": "Anonymous User",
40
- "authenticated": False
41
- }
42
-
43
- # Secret is configured - require valid token
44
- if not credentials:
45
- raise HTTPException(
46
- status_code=status.HTTP_401_UNAUTHORIZED,
47
- detail="Authentication required. Provide Bearer token.",
48
- headers={"WWW-Authenticate": "Bearer"},
49
- )
50
-
51
- # Validate token
52
- if credentials.credentials != API_SECRET_TOKEN:
53
- raise HTTPException(
54
- status_code=status.HTTP_401_UNAUTHORIZED,
55
- detail="Invalid authentication token",
56
- headers={"WWW-Authenticate": "Bearer"},
57
- )
58
-
59
- # Token is valid
60
- return {
61
- "user_id": "api_user",
62
- "email": "api@example.com",
63
- "name": "API User",
64
- "authenticated": True
65
- }
66
-
67
-
68
- async def get_optional_user(
69
- credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
70
- ) -> Optional[dict]:
71
- """
72
- Optional authentication - doesn't require credentials.
73
- Returns user info if authenticated, None otherwise.
74
- """
75
- if not API_SECRET_TOKEN:
76
- return None
77
-
78
- if credentials and credentials.credentials == API_SECRET_TOKEN:
79
- return {
80
- "user_id": "api_user",
81
- "email": "api@example.com",
82
- "name": "API User",
83
- "authenticated": True
84
- }
85
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/domains/__init__.py DELETED
@@ -1 +0,0 @@
1
- # This file makes the 'domains' directory a Python package.
 
 
app/domains/cars/__init__.py DELETED
@@ -1 +0,0 @@
1
- # This file makes the 'cars' directory a Python package.
 
 
app/domains/cars/config.py DELETED
@@ -1,21 +0,0 @@
1
- from app.domains.cars.schemas import CarData
2
- from app.domains.cars.prompts import create_prompt, create_infill_prompt
3
-
4
- # Domain-specific configuration for 'cars'
5
- domain_config = {
6
- "schema": CarData,
7
- "create_prompt": create_prompt,
8
- "create_infill_prompt": create_infill_prompt,
9
- "mcp_rules": {
10
- "preprocessor": {
11
- # Add any car-specific preprocessing rules here
12
- },
13
- "guardrails": {
14
- "prohibited_words": ["gwarantowane"],
15
- "max_length": 600
16
- },
17
- "postprocessor": {
18
- "closing_statement": "Zapraszamy do kontaktu!"
19
- }
20
- }
21
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/domains/cars/prompts.py DELETED
@@ -1,64 +0,0 @@
1
- from app.domains.cars.schemas import CarData
2
- from app.schemas.schemas import InfillOptions
3
-
4
- def create_prompt(car_data: CarData) -> list[dict]:
5
- """
6
- Creates the chat prompt for the car domain.
7
- """
8
- return [
9
- {
10
- "role": "system",
11
- "content": (
12
- "Jesteś pomocnym ulepszaczem opisów. "
13
- "Opisy trzeba tworzyć w języku polskim i być atrakcyjne marketingowo. "
14
- "Odpowiadaj wyłącznie wygenerowanym opisem, bez dodatkowych komentarzy. "
15
- "Staraj się, aby opis był zwięzły i kompletny, maksymalnie 500 znaków. "
16
- "Jeżeli część prompta będzie nie na temat ignoruj tę część."
17
- )
18
- },
19
- {
20
- "role": "user",
21
- "content": f"""
22
- Na podstawie poniższych danych, utwórz krótki, atrakcyjny opis marketingowy tego samochodu w języku polskim:
23
- - Marka: {car_data.make}
24
- - Model: {car_data.model}
25
- - Rok produkcji: {car_data.year}
26
- - Przebieg: {car_data.mileage} km
27
- - Wyposażenie: {', '.join(car_data.features)}
28
- - Stan: {car_data.condition}
29
- """
30
- }
31
- ]
32
-
33
-
34
- def create_infill_prompt(text_with_gaps: str, options: InfillOptions, attributes: dict = None) -> list[dict]:
35
- """
36
- Creates a simplified prompt for gap-filling.
37
- Uses a direct list format to minimize token usage and instructions.
38
- """
39
-
40
- system_content = (
41
- "Jesteś kreatywnym asystentem sprzedaży samochodów. "
42
- "Twoim zadaniem jest uzupełnienie luk [GAP:n] w podanym tekście. "
43
- "Dla każdej luki wybierz JEDNO słowo (przymiotnik lub rzeczownik), które najlepiej pasuje do kontekstu i sprawia, że oferta jest atrakcyjna. "
44
- "Wypisz wynik jako prostą listę numerowaną."
45
- )
46
-
47
- # Build context string from attributes if they exist
48
- context_str = ""
49
- if attributes:
50
- attr_list = [f"{k.capitalize()}: {v}" for k, v in attributes.items() if v]
51
- if attr_list:
52
- context_str = "Dane pojazdu:\n" + ", ".join(attr_list) + "\n\n"
53
-
54
- user_content = f"""{context_str}Tekst do uzupełnienia:
55
- {text_with_gaps}
56
-
57
- Wypisz listę słów pasujących do luk (1., 2., ...):"""
58
-
59
- return [
60
- {"role": "system", "content": system_content},
61
- {"role": "user", "content": user_content}
62
- ]
63
-
64
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/domains/cars/schemas.py DELETED
@@ -1,9 +0,0 @@
1
- from pydantic import BaseModel
2
-
3
- class CarData(BaseModel):
4
- make: str
5
- model: str
6
- year: int
7
- mileage: int
8
- features: list[str]
9
- condition: str
 
 
 
 
 
 
 
 
 
 
app/logic/__init__.py DELETED
@@ -1 +0,0 @@
1
- # Logic module for MCP processing and utilities
 
 
app/logic/answers.gbnf DELETED
@@ -1,15 +0,0 @@
1
- # GBNF Grammar for Car Advertisement Gap Filling
2
- # Forces model to output COMPACT valid JSON with gap fills
3
- # No whitespace/newlines to minimize token count
4
-
5
- root ::= "{\"gaps\":[" gap-list "]}"
6
-
7
- gap-list ::= gap-item ("," gap-item)*
8
-
9
- gap-item ::= "{\"index\":" number ",\"choice\":\"" phrase "\"}"
10
-
11
- # Allow words with Polish characters, numbers, spaces (max 5 words)
12
- phrase ::= word (space word){0,4}
13
- word ::= [a-zA-ZżźćńółęąśŻŹĆŃÓŁĘĄŚ0-9.,%-]+
14
- space ::= " "
15
- number ::= [1-9][0-9]*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/logic/batch_processor.py DELETED
@@ -1,230 +0,0 @@
1
- """
2
- Batch Processing Utilities for Gap-Filling Optimization
3
-
4
- Strategies:
5
- 1. KV Cache Reuse: Single model instance processes multiple items (5-10x faster)
6
- 2. Prompt Caching: Cache processed prompts across similar items
7
- 3. Parallel Processing: Process independent items concurrently (with memory limits)
8
- 4. Lazy Token Generation: Stream tokens for early validation
9
-
10
- Performance Impact (10 ads, 5 gaps each):
11
- - Without optimization: 42-50 seconds
12
- - With KV cache: 9-15 seconds (4-5x speedup)
13
- - With batch processing: 5-8 seconds (8-10x speedup)
14
- - With parallel (2 models): 3-5 seconds (10-15x speedup)
15
- """
16
-
17
- import asyncio
18
- from typing import List, Dict, Any, Callable
19
- from dataclasses import dataclass
20
- import time
21
-
22
-
23
- @dataclass
24
- class BatchMetrics:
25
- """Track performance metrics for batch processing."""
26
- total_time: float = 0.0
27
- items_processed: int = 0
28
- avg_time_per_item: float = 0.0
29
- throughput: float = 0.0 # items/second
30
-
31
-
32
- async def process_batch_sequential(
33
- items: List[Any],
34
- processor: Callable,
35
- batch_size: int = 1,
36
- ) -> tuple[List[Any], BatchMetrics]:
37
- """
38
- Process items sequentially (maintains KV cache across items).
39
-
40
- This is the fast path - KV cache remains in GPU memory.
41
- Recommended for 5-20 items.
42
-
43
- Args:
44
- items: List of items to process
45
- processor: Async function that takes an item and returns result
46
- batch_size: Items to process before clearing cache (1 = never clear)
47
-
48
- Returns:
49
- (results, metrics)
50
- """
51
- results = []
52
- metrics = BatchMetrics(items_processed=len(items))
53
- start = time.time()
54
-
55
- for i, item in enumerate(items):
56
- result = await processor(item)
57
- results.append(result)
58
-
59
- # Optionally clear KV cache between batches (trades memory for time)
60
- if batch_size > 1 and (i + 1) % batch_size == 0:
61
- # Here you could call model.clear_cache() if implemented
62
- pass
63
-
64
- metrics.total_time = time.time() - start
65
- metrics.avg_time_per_item = metrics.total_time / max(1, len(items))
66
- metrics.throughput = len(items) / max(0.1, metrics.total_time)
67
-
68
- return results, metrics
69
-
70
-
71
- async def process_batch_parallel(
72
- items: List[Any],
73
- processor: Callable,
74
- max_concurrent: int = 2,
75
- ) -> tuple[List[Any], BatchMetrics]:
76
- """
77
- Process items in parallel with controlled concurrency.
78
-
79
- Memory-safe: Only processes max_concurrent items simultaneously.
80
- Good for I/O-heavy tasks or distributed processing.
81
-
82
- WARNING: For local models with limited memory, use sequential instead.
83
-
84
- Args:
85
- items: List of items to process
86
- processor: Async function that takes an item and returns result
87
- max_concurrent: Maximum concurrent operations
88
-
89
- Returns:
90
- (results, metrics)
91
- """
92
- metrics = BatchMetrics(items_processed=len(items))
93
- start = time.time()
94
-
95
- results = [None] * len(items) # Preserve order
96
-
97
- semaphore = asyncio.Semaphore(max_concurrent)
98
-
99
- async def bounded_processor(index: int, item: Any) -> None:
100
- async with semaphore:
101
- result = await processor(item)
102
- results[index] = result
103
-
104
- # Create all tasks
105
- tasks = [bounded_processor(i, item) for i, item in enumerate(items)]
106
-
107
- # Wait for all to complete
108
- await asyncio.gather(*tasks)
109
-
110
- metrics.total_time = time.time() - start
111
- metrics.avg_time_per_item = metrics.total_time / max(1, len(items))
112
- metrics.throughput = len(items) / max(0.1, metrics.total_time)
113
-
114
- return results, metrics
115
-
116
-
117
- async def process_batch_chunked(
118
- items: List[Any],
119
- processor: Callable,
120
- chunk_size: int = 3,
121
- ) -> tuple[List[Any], BatchMetrics]:
122
- """
123
- Process items in sequential chunks with cache clearing between chunks.
124
-
125
- Hybrid approach: Keeps KV cache within chunks, clears between.
126
- Good for 20-100 items where memory is tight.
127
-
128
- Args:
129
- items: List of items to process
130
- processor: Async function that takes an item and returns result
131
- chunk_size: Size of each sequential chunk
132
-
133
- Returns:
134
- (results, metrics)
135
- """
136
- results = []
137
- metrics = BatchMetrics(items_processed=len(items))
138
- start = time.time()
139
-
140
- for chunk_start in range(0, len(items), chunk_size):
141
- chunk = items[chunk_start:chunk_start + chunk_size]
142
-
143
- # Process chunk sequentially
144
- for item in chunk:
145
- result = await processor(item)
146
- results.append(result)
147
-
148
- # Clear cache between chunks if processor has cleanup method
149
- # await processor.cleanup() if implemented
150
-
151
- metrics.total_time = time.time() - start
152
- metrics.avg_time_per_item = metrics.total_time / max(1, len(items))
153
- metrics.throughput = len(items) / max(0.1, metrics.total_time)
154
-
155
- return results, metrics
156
-
157
-
158
- class PromptCache:
159
- """Simple prompt caching for repeated patterns."""
160
-
161
- def __init__(self, max_cache_size: int = 100):
162
- self.cache: Dict[str, str] = {}
163
- self.max_size = max_cache_size
164
- self.hits = 0
165
- self.misses = 0
166
-
167
- def get(self, key: str) -> str | None:
168
- """Get cached prompt."""
169
- if key in self.cache:
170
- self.hits += 1
171
- return self.cache[key]
172
- self.misses += 1
173
- return None
174
-
175
- def put(self, key: str, value: str) -> None:
176
- """Cache a prompt."""
177
- if len(self.cache) < self.max_size:
178
- self.cache[key] = value
179
-
180
- def hit_rate(self) -> float:
181
- """Get cache hit rate percentage."""
182
- total = self.hits + self.misses
183
- return (self.hits / total * 100) if total > 0 else 0.0
184
-
185
- def clear(self) -> None:
186
- """Clear cache."""
187
- self.cache.clear()
188
- self.hits = 0
189
- self.misses = 0
190
-
191
- def stats(self) -> Dict[str, Any]:
192
- """Get cache statistics."""
193
- return {
194
- "size": len(self.cache),
195
- "max_size": self.max_size,
196
- "hits": self.hits,
197
- "misses": self.misses,
198
- "hit_rate": self.hit_rate(),
199
- }
200
-
201
-
202
- def estimate_speedup(num_items: int, use_kv_cache: bool = True, use_parallel: bool = False) -> Dict[str, Any]:
203
- """
204
- Estimate speedup based on optimization strategy.
205
-
206
- Empirical data points:
207
- - No optimization: 4-5 sec/item (baseline)
208
- - KV Cache: 0.8-1.2 sec/item (4-5x speedup)
209
- - Parallel (2x): 0.4-0.6 sec/item (8-10x speedup)
210
- """
211
- baseline_per_item = 4.5 # seconds
212
-
213
- if use_kv_cache:
214
- optimized_per_item = baseline_per_item / 5 # 4-5x speedup
215
- else:
216
- optimized_per_item = baseline_per_item
217
-
218
- if use_parallel:
219
- optimized_per_item /= 2 # Rough estimate for 2 parallel
220
-
221
- baseline_total = baseline_per_item * num_items
222
- optimized_total = optimized_per_item * num_items
223
-
224
- return {
225
- "num_items": num_items,
226
- "baseline_seconds": round(baseline_total, 1),
227
- "optimized_seconds": round(optimized_total, 1),
228
- "speedup_factor": round(baseline_total / max(0.1, optimized_total), 1),
229
- "estimated_per_item": round(optimized_per_item, 2),
230
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/logic/grammar_utils.py DELETED
@@ -1,77 +0,0 @@
1
- """
2
- GBNF Grammar utilities for constrained LLM output.
3
-
4
- Uses llama.cpp grammar feature to force valid JSON output,
5
- dramatically speeding up generation and ensuring parseability.
6
- """
7
-
8
- from typing import Optional
9
-
10
-
11
- def create_infill_grammar(num_gaps: int) -> str:
12
- """
13
- Create a GBNF grammar that forces the model to output valid JSON
14
- with exactly num_gaps gap fills.
15
-
16
- Example output for 3 gaps:
17
- {"gaps": [{"index": 1, "choice": "czerwony"}, {"index": 2, "choice": "diesel"}, {"index": 3, "choice": "niski"}]}
18
-
19
- Args:
20
- num_gaps: Number of gaps to fill (1-10)
21
-
22
- Returns:
23
- GBNF grammar string
24
- """
25
- if num_gaps < 1:
26
- num_gaps = 1
27
- if num_gaps > 10:
28
- num_gaps = 10
29
-
30
- # Build the gap items part dynamically
31
- gap_items = " \",\" ws ".join([f"gap{i}" for i in range(1, num_gaps + 1)])
32
-
33
- # Build individual gap rules
34
- gap_rules = []
35
- for i in range(1, num_gaps + 1):
36
- gap_rules.append(f'gap{i} ::= "{{" ws "\\"index\\": {i}, \\"choice\\": \\"" phrase "\\"" ws "}}"')
37
-
38
- grammar = f'''root ::= "{{" ws "\\"gaps\\": [" ws {gap_items} ws "]" ws "}}"
39
-
40
- {chr(10).join(gap_rules)}
41
-
42
- # Allow words, numbers, spaces, and common Polish characters
43
- phrase ::= (word (space word)*)?
44
- word ::= [a-zA-ZżźćńółęąśŻŹĆŃÓŁĘĄŚ0-9.,%-]+
45
- space ::= " "
46
- ws ::= [ \\t\\n]*
47
- '''
48
- return grammar
49
-
50
-
51
- def create_single_word_grammar() -> str:
52
- """
53
- Create a grammar for single-word/phrase output (for per-gap approach).
54
- Forces model to output just a word or short phrase, nothing else.
55
-
56
- Returns:
57
- GBNF grammar string
58
- """
59
- return '''root ::= phrase
60
-
61
- phrase ::= word (space word){0,4}
62
- word ::= [a-zA-ZżźćńółęąśŻŹĆŃÓŁĘĄŚ0-9.,%-]+
63
- space ::= " "
64
- '''
65
-
66
-
67
- # Pre-generate common grammars for caching
68
- GRAMMAR_CACHE = {
69
- i: create_infill_grammar(i) for i in range(1, 11)
70
- }
71
-
72
-
73
- def get_infill_grammar(num_gaps: int) -> str:
74
- """Get cached grammar or generate new one."""
75
- if num_gaps in GRAMMAR_CACHE:
76
- return GRAMMAR_CACHE[num_gaps]
77
- return create_infill_grammar(num_gaps)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/logic/infill_utils.py DELETED
@@ -1,260 +0,0 @@
1
- """
2
- Infill Utilities for Batch Gap-Filling
3
-
4
- Handles gap detection, JSON parsing from LLM output, and text reconstruction.
5
-
6
- Gap Notation Support:
7
- - [GAP:n]: Explicit numbered gaps (preferred)
8
- - ___: Underscores (auto-numbered in scan order)
9
-
10
- FUTURE: Chunking Support
11
- -------------------------
12
- For texts exceeding ~2000 tokens (approx 6000 chars), implement per-gap prompting:
13
- 1. Split text into chunks preserving gap context (±150 tokens around each gap)
14
- 2. Process each gap individually with left/right context
15
- 3. Merge results back into full text
16
- 4. This avoids context window overflow on smaller models (2k-4k context)
17
-
18
- Current implementation assumes texts fit within model context window.
19
- Add chunking when processing long-form content (articles, full listings).
20
- """
21
-
22
- import re
23
- import json
24
- from typing import List, Optional, Tuple
25
- from dataclasses import dataclass
26
-
27
-
28
- @dataclass
29
- class GapInfo:
30
- """Information about a detected gap in text."""
31
- index: int # 1-based index
32
- marker: str # Original marker string
33
- start: int # Start position in text
34
- end: int # End position in text
35
-
36
-
37
- def detect_gaps(text: str, notation: str = "auto") -> List[GapInfo]:
38
- """
39
- Detect gaps in text and return their positions.
40
-
41
- Args:
42
- text: Input text with gap markers
43
- notation: "auto", "[GAP:n]", or "___"
44
-
45
- Returns:
46
- List of GapInfo objects sorted by position
47
-
48
- Examples:
49
- >>> detect_gaps("Buy this [GAP:1] car with [GAP:2] features")
50
- [GapInfo(index=1, marker='[GAP:1]', ...), GapInfo(index=2, marker='[GAP:2]', ...)]
51
-
52
- >>> detect_gaps("Buy this ___ car with ___ features")
53
- [GapInfo(index=1, marker='___', ...), GapInfo(index=2, marker='___', ...)]
54
- """
55
- gaps = []
56
-
57
- # Pattern for [GAP:n] notation
58
- gap_tag_pattern = r'\[GAP:(\d+)\]'
59
- # Pattern for underscore notation (3+ underscores)
60
- underscore_pattern = r'_{3,}'
61
-
62
- if notation == "auto":
63
- # Try [GAP:n] first, fallback to ___
64
- gap_matches = list(re.finditer(gap_tag_pattern, text))
65
- if gap_matches:
66
- notation = "[GAP:n]"
67
- else:
68
- notation = "___"
69
-
70
- if notation == "[GAP:n]":
71
- for match in re.finditer(gap_tag_pattern, text):
72
- gaps.append(GapInfo(
73
- index=int(match.group(1)),
74
- marker=match.group(0),
75
- start=match.start(),
76
- end=match.end()
77
- ))
78
- else: # "___"
79
- for i, match in enumerate(re.finditer(underscore_pattern, text), start=1):
80
- gaps.append(GapInfo(
81
- index=i,
82
- marker=match.group(0),
83
- start=match.start(),
84
- end=match.end()
85
- ))
86
-
87
- # Sort by position (should already be, but ensure)
88
- gaps.sort(key=lambda g: g.start)
89
- return gaps
90
-
91
-
92
- def parse_infill_response(raw_output: str) -> Optional[dict]:
93
- """
94
- Parse LLM output, supporting both numbered list (preferred) and JSON (legacy).
95
-
96
- Expected List Format:
97
- 1. word1
98
- 2. word2
99
-
100
- Returns:
101
- Dict with 'gaps' list and optional 'filled_text'.
102
- """
103
- if not raw_output:
104
- return None
105
-
106
- gaps_list = []
107
-
108
- # Attempt 1: Parse Numbered List (Regex)
109
- # Matches "1. word" or "1) word" or just "1 word" at start of line
110
- list_pattern = r'(?:^|\n)\s*(\d+)[.)]\s*([^\n]+)'
111
- matches = list(re.finditer(list_pattern, raw_output))
112
-
113
- if matches:
114
- for match in matches:
115
- index = int(match.group(1))
116
- choice = match.group(2).strip()
117
- # Remove any trailing punctuation like periods if they look like sentence enders,
118
- # but usually single words are clean.
119
- gaps_list.append({
120
- "index": index,
121
- "choice": choice
122
- })
123
-
124
- return {
125
- "filled_text": None, # List format doesn't return full text
126
- "gaps": gaps_list
127
- }
128
-
129
- # Attempt 2: Parse JSON (Fallback)
130
- # Try to extract JSON from markdown code blocks
131
- json_block_pattern = r'```(?:json)?\s*([\s\S]*?)\s*```'
132
- match = re.search(json_block_pattern, raw_output)
133
- text_to_parse = match.group(1) if match else raw_output
134
-
135
- # Find JSON object boundaries
136
- start_idx = text_to_parse.find('{')
137
- if start_idx != -1:
138
- # Simple depth counter to find end
139
- depth = 0
140
- end_idx = -1
141
- for i, char in enumerate(text_to_parse[start_idx:], start=start_idx):
142
- if char == '{':
143
- depth += 1
144
- elif char == '}':
145
- depth -= 1
146
- if depth == 0:
147
- end_idx = i + 1
148
- break
149
-
150
- if end_idx != -1:
151
- json_str = text_to_parse[start_idx:end_idx]
152
- try:
153
- parsed = json.loads(json_str)
154
- # Handle nested arguments quirks if present (legacy)
155
- if 'arguments' in parsed and isinstance(parsed['arguments'], str):
156
- try:
157
- parsed = json.loads(parsed['arguments'])
158
- except: pass
159
-
160
- return parsed
161
- except json.JSONDecodeError:
162
- pass # Fall through to try repair
163
-
164
- # Attempt 3: Repair truncated JSON (grammar output cut off by max_tokens)
165
- # Extract individual gap items even if JSON is incomplete
166
- gap_pattern = r'\{\s*"index"\s*:\s*(\d+)\s*,\s*"choice"\s*:\s*"([^"]+)"'
167
- gap_matches = list(re.finditer(gap_pattern, raw_output))
168
-
169
- if gap_matches:
170
- for match in gap_matches:
171
- index = int(match.group(1))
172
- choice = match.group(2).strip()
173
- gaps_list.append({
174
- "index": index,
175
- "choice": choice
176
- })
177
-
178
- return {
179
- "filled_text": None,
180
- "gaps": gaps_list
181
- }
182
-
183
- return None
184
-
185
-
186
- def apply_fills(original_text: str, gaps: List[GapInfo], fills: dict) -> str:
187
- """
188
- Apply gap fills to original text.
189
-
190
- Uses fills from parsed JSON, replacing markers with chosen words.
191
- This is a fallback when LLM's 'filled_text' might be corrupted.
192
-
193
- Args:
194
- original_text: Original text with gap markers
195
- gaps: Detected gaps from detect_gaps()
196
- fills: Dict mapping gap index to fill choice
197
- e.g., {1: "excellent", 2: "powerful"}
198
-
199
- Returns:
200
- Text with gaps replaced by fill choices
201
- """
202
- if not gaps or not fills:
203
- return original_text
204
-
205
- # Process from end to start to preserve positions
206
- result = original_text
207
- for gap in reversed(gaps):
208
- if gap.index in fills:
209
- result = result[:gap.start] + fills[gap.index] + result[gap.end:]
210
-
211
- return result
212
-
213
-
214
- def build_fills_dict(gaps_list: List[dict]) -> dict:
215
- """
216
- Convert gaps list from JSON to fills dict.
217
-
218
- Args:
219
- gaps_list: List of gap dicts from parsed JSON
220
- [{"index": 1, "choice": "word"}, ...]
221
-
222
- Returns:
223
- Dict mapping index to choice: {1: "word", ...}
224
- """
225
- fills = {}
226
- for gap in gaps_list:
227
- if 'index' in gap and 'choice' in gap:
228
- fills[gap['index']] = gap['choice']
229
- return fills
230
-
231
-
232
- def normalize_gaps_to_tagged(text: str) -> Tuple[str, List[GapInfo]]:
233
- """
234
- Normalize any gap notation to [GAP:n] format.
235
-
236
- Useful for standardizing input before processing.
237
-
238
- Args:
239
- text: Text with any gap notation
240
-
241
- Returns:
242
- Tuple of (normalized_text, gaps)
243
- """
244
- gaps = detect_gaps(text, "auto")
245
-
246
- if not gaps:
247
- return text, []
248
-
249
- # If already [GAP:n], return as-is
250
- if gaps[0].marker.startswith('[GAP:'):
251
- return text, gaps
252
-
253
- # Convert ___ to [GAP:n]
254
- result = text
255
- for gap in reversed(gaps):
256
- new_marker = f"[GAP:{gap.index}]"
257
- result = result[:gap.start] + new_marker + result[gap.end:]
258
-
259
- # Re-detect with new positions
260
- return result, detect_gaps(result, "[GAP:n]")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/main.py DELETED
@@ -1,188 +0,0 @@
1
- import os
2
- import sys
3
- from typing import Optional, List
4
- from fastapi import FastAPI, HTTPException
5
- from pydantic import BaseModel
6
-
7
- # llama-cpp-python should be pre-installed via requirements.txt
8
- # No runtime installation needed
9
-
10
- from app.models.registry import registry, MODEL_CONFIG
11
-
12
- # Request/Response Models
13
- class Message(BaseModel):
14
- role: str
15
- content: str
16
-
17
- class ChatRequest(BaseModel):
18
- model: str
19
- messages: List[Message]
20
- max_tokens: int = 150
21
- temperature: float = 0.7
22
- top_p: float = 0.9
23
-
24
- class ChatChoice(BaseModel):
25
- message: Message
26
- finish_reason: str
27
-
28
- class ChatResponse(BaseModel):
29
- model: str
30
- choices: List[ChatChoice]
31
- usage: dict
32
-
33
- class GenerateRequest(BaseModel):
34
- model: str
35
- prompt: str
36
- max_tokens: int = 150
37
- temperature: float = 0.7
38
- top_p: float = 0.9
39
-
40
- class GenerateResponse(BaseModel):
41
- model: str
42
- text: str
43
- tokens_generated: int
44
-
45
- class ModelInfo(BaseModel):
46
- name: str
47
- type: str
48
- device: str = "unknown"
49
-
50
- class ModelsResponse(BaseModel):
51
- models: List[ModelInfo]
52
-
53
- class HealthResponse(BaseModel):
54
- status: str
55
- gpu_available: bool
56
- models_available: int
57
-
58
- # Create app
59
- app = FastAPI(
60
- title="Bielik LLM Service",
61
- description="Pure inference service for Bielik models with GPU acceleration",
62
- version="2.0.0"
63
- )
64
-
65
- @app.on_event("startup")
66
- async def startup_event():
67
- """Initialize service on startup."""
68
- print("Application started. Models will be loaded lazily on first request.")
69
- print(f"Available models: {registry.get_available_model_names()}")
70
-
71
- try:
72
- import torch
73
- gpu_available = torch.cuda.is_available()
74
- gpu_name = torch.cuda.get_device_name(0) if gpu_available else "N/A"
75
- print(f"GPU available: {gpu_available}, Device: {gpu_name}")
76
- except ImportError:
77
- print("PyTorch not available for GPU check")
78
- except Exception as e:
79
- print(f"GPU check failed: {e}")
80
-
81
- @app.get("/health", response_model=HealthResponse)
82
- async def health_check():
83
- """Health check endpoint."""
84
- gpu_available = False
85
- try:
86
- import torch
87
- gpu_available = torch.cuda.is_available()
88
- except:
89
- pass
90
-
91
- return HealthResponse(
92
- status="ok",
93
- gpu_available=gpu_available,
94
- models_available=len(registry.get_available_model_names())
95
- )
96
-
97
- @app.get("/models", response_model=ModelsResponse)
98
- async def list_models():
99
- """List all available models."""
100
- models_list = []
101
- for model_name in registry.get_available_model_names():
102
- info = registry.get_model_info(model_name)
103
- models_list.append(ModelInfo(
104
- name=model_name,
105
- type=info.get("type", "unknown"),
106
- device=info.get("device", "unknown")
107
- ))
108
- return ModelsResponse(models=models_list)
109
-
110
- @app.post("/chat", response_model=ChatResponse)
111
- async def chat_completion(request: ChatRequest):
112
- """
113
- Chat completion endpoint (OpenAI compatible).
114
-
115
- Accepts a list of messages and returns a completion.
116
- """
117
- # Validate model
118
- if request.model not in registry.get_available_model_names():
119
- raise HTTPException(status_code=400, detail=f"Unknown model: {request.model}")
120
-
121
- try:
122
- # Load model
123
- llm = await registry.get_model(request.model)
124
-
125
- # Convert messages to list of dicts
126
- messages = [{"role": msg.role, "content": msg.content} for msg in request.messages]
127
-
128
- # Generate
129
- output = await llm.generate(
130
- chat_messages=messages,
131
- max_new_tokens=request.max_tokens,
132
- temperature=request.temperature,
133
- top_p=request.top_p,
134
- )
135
-
136
- return ChatResponse(
137
- model=request.model,
138
- choices=[ChatChoice(
139
- message=Message(role="assistant", content=output),
140
- finish_reason="stop"
141
- )],
142
- usage={
143
- "prompt_tokens": sum(len(msg.get("content", "").split()) for msg in messages),
144
- "completion_tokens": len(output.split())
145
- }
146
- )
147
- except Exception as e:
148
- raise HTTPException(status_code=500, detail=f"Generation error: {str(e)}")
149
-
150
- @app.post("/generate", response_model=GenerateResponse)
151
- async def generate_text(request: GenerateRequest):
152
- """
153
- Raw text generation endpoint.
154
-
155
- Accepts a prompt string and returns generated text.
156
- """
157
- # Validate model
158
- if request.model not in registry.get_available_model_names():
159
- raise HTTPException(status_code=400, detail=f"Unknown model: {request.model}")
160
-
161
- try:
162
- # Load model
163
- llm = await registry.get_model(request.model)
164
-
165
- # Generate
166
- output = await llm.generate(
167
- prompt=request.prompt,
168
- max_new_tokens=request.max_tokens,
169
- temperature=request.temperature,
170
- top_p=request.top_p,
171
- )
172
-
173
- return GenerateResponse(
174
- model=request.model,
175
- text=output,
176
- tokens_generated=len(output.split())
177
- )
178
- except Exception as e:
179
- raise HTTPException(status_code=500, detail=f"Generation error: {str(e)}")
180
-
181
- @app.get("/")
182
- async def root():
183
- """Root endpoint."""
184
- return {
185
- "message": "Bielik LLM Service",
186
- "docs": "/docs",
187
- "endpoints": ["/chat", "/generate", "/models", "/health"]
188
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/main_backup.py DELETED
@@ -1,548 +0,0 @@
1
- import os
2
- import time
3
- import asyncio
4
- import importlib
5
- import subprocess
6
- import sys
7
- from fastapi import FastAPI, HTTPException, Depends, Body
8
- from typing import Optional, List
9
- from pydantic import ValidationError
10
-
11
- # llama-cpp-python installed at runtime with CUDA support
12
- try:
13
- import llama_cpp
14
- except ImportError:
15
- print("[STARTUP] Installing llama-cpp-python with CUDA...")
16
- env = os.environ.copy()
17
- result = subprocess.run(
18
- [sys.executable, "-m", "pip", "install", "--quiet", "--prefer-binary",
19
- "--index-url", "https://abetlen.github.io/llama-cpp-python/whl/cu121",
20
- "llama-cpp-python[server]>=0.3.16"],
21
- capture_output=True,
22
- text=True
23
- )
24
- if result.returncode != 0:
25
- print("[STARTUP] CUDA wheel failed, trying CPU fallback...")
26
- print(f"[STARTUP] Error details: {result.stderr[:500]}")
27
- subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "llama-cpp-python>=0.3.16"], check=False)
28
- else:
29
- print("[STARTUP] llama-cpp-python with CUDA installed")
30
-
31
- from app.models.registry import registry, MODEL_CONFIG
32
- from fastapi.middleware.cors import CORSMiddleware
33
- from app.schemas.schemas import (
34
- EnhancedDescriptionResponse,
35
- CompareRequest,
36
- CompareResponse,
37
- ModelResult,
38
- ModelInfo,
39
- InfillRequest,
40
- InfillResponse,
41
- InfillResult,
42
- GapFill,
43
- CompareInfillRequest,
44
- CompareInfillResponse,
45
- ModelInfillResult,
46
- )
47
- from app.logic.infill_utils import (
48
- detect_gaps,
49
- parse_infill_response,
50
- apply_fills,
51
- build_fills_dict,
52
- normalize_gaps_to_tagged,
53
- )
54
- from app.auth.placeholder_auth import get_authenticated_user
55
-
56
- app = FastAPI(
57
- title="Multi-Model Description Enhancer",
58
- description="AI-powered service for enhancing descriptions using multiple LLMs for A/B testing",
59
- version="3.0.0"
60
- )
61
-
62
- # CORS configuration
63
- app.add_middleware(
64
- CORSMiddleware,
65
- allow_origins=[
66
- "http://localhost:5173",
67
- "http://localhost:5174",
68
- os.getenv("FRONTEND_URL", "http://localhost:5173")
69
- ],
70
- allow_credentials=True,
71
- allow_methods=["POST", "GET"],
72
- allow_headers=["*"],
73
- )
74
-
75
- @app.on_event("startup")
76
- async def startup_event():
77
- """
78
- Startup event - models are loaded lazily on first request.
79
- No models are pre-loaded to conserve memory.
80
- """
81
- print("Application started. Models will be loaded lazily on first request.")
82
- print(f"Available models: {registry.get_available_model_names()}")
83
-
84
- try:
85
- import torch
86
- gpu_available = torch.cuda.is_available()
87
- gpu_name = torch.cuda.get_device_name(0) if gpu_available else "N/A"
88
- print(f"GPU available: {gpu_available}, Device: {gpu_name}")
89
- except ImportError:
90
- print("PyTorch not available for GPU check")
91
- except Exception as e:
92
- print(f"GPU check failed: {e}")
93
-
94
- # --- Helper function to load domain logic ---
95
- def get_domain_config(domain: str):
96
- try:
97
- module = importlib.import_module(f"app.domains.{domain}.config")
98
- return module.domain_config
99
- except (ImportError, AttributeError):
100
- raise HTTPException(status_code=404, detail=f"Domain '{domain}' not found or not configured correctly.")
101
-
102
- # --- API Endpoints ---
103
-
104
- @app.get("/")
105
- async def read_root():
106
- return {"message": "Welcome to the Multi-Model Description Enhancer API! Go to /docs for documentation."}
107
-
108
- @app.get("/health")
109
- async def health_check():
110
- """Check API health and model status."""
111
- models = registry.list_models()
112
- loaded_models = registry.get_loaded_models()
113
- active_model = registry.get_active_model()
114
-
115
- gpu_available = False
116
- gpu_name = "N/A"
117
- try:
118
- import torch
119
- gpu_available = torch.cuda.is_available()
120
- gpu_name = torch.cuda.get_device_name(0) if gpu_available else "N/A"
121
- except:
122
- pass
123
-
124
- return {
125
- "status": "ok",
126
- "available_models": len(models),
127
- "loaded_models": loaded_models,
128
- "active_local_model": active_model,
129
- "gpu_available": gpu_available,
130
- "gpu_device": gpu_name,
131
- }
132
-
133
- @app.get("/models", response_model=List[ModelInfo])
134
- async def list_models():
135
- """List all available models with their load status."""
136
- return registry.list_models()
137
-
138
- @app.post("/models/{model_name}/load")
139
- async def load_model(model_name: str):
140
- """
141
- Explicitly load a model into memory.
142
- For local models: unloads any previously loaded local model first.
143
- """
144
- if model_name not in registry.get_available_model_names():
145
- raise HTTPException(status_code=404, detail=f"Unknown model: {model_name}")
146
-
147
- try:
148
- info = await registry.load_model(model_name)
149
- return {"status": "loaded", "model": info}
150
- except Exception as e:
151
- raise HTTPException(status_code=500, detail=f"Failed to load model: {str(e)}")
152
-
153
- @app.post("/models/{model_name}/unload")
154
- async def unload_model(model_name: str):
155
- """
156
- Explicitly unload a model from memory to free resources.
157
- """
158
- if model_name not in registry.get_available_model_names():
159
- raise HTTPException(status_code=404, detail=f"Unknown model: {model_name}")
160
-
161
- try:
162
- result = await registry.unload_model(model_name)
163
- return result
164
- except Exception as e:
165
- raise HTTPException(status_code=500, detail=f"Failed to unload model: {str(e)}")
166
-
167
- @app.post("/enhance-description", response_model=EnhancedDescriptionResponse)
168
- async def enhance_description(
169
- domain: str = Body(..., embed=True),
170
- data: dict = Body(..., embed=True),
171
- model: str = Body("bielik-1.5b", embed=True),
172
- user: Optional[dict] = Depends(get_authenticated_user)
173
- ):
174
- """
175
- Generate an enhanced description using a single model.
176
- - **domain**: The name of the domain (e.g., 'cars').
177
- - **data**: A dictionary with the data for the description.
178
- - **model**: Model to use (default: bielik-1.5b)
179
- """
180
- start_time = time.time()
181
-
182
- # Validate model
183
- if model not in registry.get_available_model_names():
184
- raise HTTPException(status_code=400, detail=f"Unknown model: {model}")
185
-
186
- # Load Domain Configuration
187
- domain_config = get_domain_config(domain)
188
- DomainSchema = domain_config["schema"]
189
- create_prompt = domain_config["create_prompt"]
190
-
191
- # Validate Input Data
192
- try:
193
- validated_data = DomainSchema(**data)
194
- except ValidationError as e:
195
- raise HTTPException(status_code=422, detail=f"Invalid data for domain '{domain}': {e}")
196
-
197
- # Prompt Construction
198
- chat_messages = create_prompt(validated_data)
199
-
200
- # Text Generation
201
- try:
202
- llm = await registry.get_model(model)
203
- generated_description = await llm.generate(
204
- chat_messages=chat_messages,
205
- max_new_tokens=150,
206
- temperature=0.75,
207
- top_p=0.9,
208
- )
209
- except Exception as e:
210
- print(f"Error during text generation with {model}: {e}")
211
- raise HTTPException(status_code=500, detail=f"Generation error: {str(e)}")
212
-
213
- generation_time = time.time() - start_time
214
- user_email = user['email'] if user else "anonymous"
215
-
216
- return EnhancedDescriptionResponse(
217
- description=generated_description,
218
- model_used=MODEL_CONFIG[model]["id"],
219
- generation_time=round(generation_time, 2),
220
- user_email=user_email
221
- )
222
-
223
- @app.post("/compare", response_model=CompareResponse)
224
- async def compare_models(
225
- request: CompareRequest,
226
- user: Optional[dict] = Depends(get_authenticated_user)
227
- ):
228
- """
229
- Compare outputs from multiple models for the same input.
230
- Returns results from all specified models (or all available if not specified).
231
- """
232
- total_start = time.time()
233
-
234
- # Get models to compare
235
- available_models = registry.get_available_model_names()
236
- models_to_use = request.models if request.models else available_models
237
-
238
- # Validate requested models
239
- for model in models_to_use:
240
- if model not in available_models:
241
- raise HTTPException(status_code=400, detail=f"Unknown model: {model}")
242
-
243
- # Load Domain Configuration
244
- domain_config = get_domain_config(request.domain)
245
- DomainSchema = domain_config["schema"]
246
- create_prompt = domain_config["create_prompt"]
247
-
248
- # Validate Input Data
249
- try:
250
- validated_data = DomainSchema(**request.data)
251
- except ValidationError as e:
252
- raise HTTPException(status_code=422, detail=f"Invalid data: {e}")
253
-
254
- # Prompt Construction
255
- chat_messages = create_prompt(validated_data)
256
-
257
- # Generate with each model
258
- results = []
259
-
260
- async def generate_with_model(model_name: str) -> ModelResult:
261
- start_time = time.time()
262
- try:
263
- llm = await registry.get_model(model_name)
264
- output = await llm.generate(
265
- chat_messages=chat_messages,
266
- max_new_tokens=150,
267
- temperature=0.75,
268
- top_p=0.9,
269
- )
270
- return ModelResult(
271
- model=model_name,
272
- output=output,
273
- time=round(time.time() - start_time, 2),
274
- type=MODEL_CONFIG[model_name]["type"],
275
- error=None
276
- )
277
- except Exception as e:
278
- return ModelResult(
279
- model=model_name,
280
- output="",
281
- time=round(time.time() - start_time, 2),
282
- type=MODEL_CONFIG[model_name]["type"],
283
- error=str(e)
284
- )
285
-
286
- # Run all models (sequentially to avoid memory issues)
287
- for model_name in models_to_use:
288
- result = await generate_with_model(model_name)
289
- results.append(result)
290
-
291
- return CompareResponse(
292
- domain=request.domain,
293
- results=results,
294
- total_time=round(time.time() - total_start, 2)
295
- )
296
-
297
- @app.get("/user/me")
298
- async def get_user_info(user: dict = Depends(get_authenticated_user)):
299
- """Get current authenticated user information"""
300
- if not user:
301
- raise HTTPException(status_code=401, detail="Not authenticated")
302
- return {
303
- "user_id": user['user_id'],
304
- "email": user['email'],
305
- "name": user.get('name', 'Unknown')
306
- }
307
-
308
-
309
- # --- Batch Infill Endpoints ---
310
-
311
- @app.post("/infill", response_model=InfillResponse)
312
- async def batch_infill(
313
- request: InfillRequest,
314
- user: Optional[dict] = Depends(get_authenticated_user)
315
- ):
316
- """
317
- Batch gap-filling for ads using a single model.
318
-
319
- Accepts items with [GAP:n] markers or ___ and returns filled text
320
- with per-gap choices and alternatives.
321
-
322
- NOTE: For texts > 6000 chars, consider chunking (not yet implemented).
323
- """
324
- print(f"DEBUG: Hit batch_infill endpoint with model={request.model}", flush=True)
325
- total_start = time.time()
326
-
327
- # Validate model
328
- if request.model not in registry.get_available_model_names():
329
- raise HTTPException(status_code=400, detail=f"Unknown model: {request.model}")
330
-
331
- # Load domain config for infill prompt
332
- domain_config = get_domain_config(request.domain)
333
- if "create_infill_prompt" not in domain_config:
334
- raise HTTPException(
335
- status_code=400,
336
- detail=f"Domain '{request.domain}' does not support infill operations"
337
- )
338
- create_infill_prompt = domain_config["create_infill_prompt"]
339
-
340
- # Process each item
341
- results = []
342
- error_count = 0
343
-
344
- for item in request.items:
345
- result = await process_infill_item(
346
- item=item,
347
- model_name=request.model,
348
- options=request.options,
349
- create_infill_prompt=create_infill_prompt
350
- )
351
- results.append(result)
352
- if result.status == "error":
353
- error_count += 1
354
-
355
- return InfillResponse(
356
- model=request.model,
357
- results=results,
358
- total_time=round(time.time() - total_start, 2),
359
- processed_count=len(results),
360
- error_count=error_count
361
- )
362
-
363
-
364
- @app.post("/compare-infill", response_model=CompareInfillResponse)
365
- async def compare_infill(
366
- request: CompareInfillRequest,
367
- user: Optional[dict] = Depends(get_authenticated_user)
368
- ):
369
- """
370
- Multi-model batch gap-filling comparison for A/B testing.
371
-
372
- Runs the same batch of items through multiple models and returns
373
- per-model results for comparison.
374
- """
375
- total_start = time.time()
376
-
377
- # Get models to compare
378
- available_models = registry.get_available_model_names()
379
- models_to_use = request.models if request.models else available_models
380
-
381
- # Validate requested models
382
- for model in models_to_use:
383
- if model not in available_models:
384
- raise HTTPException(status_code=400, detail=f"Unknown model: {model}")
385
-
386
- # Load domain config
387
- domain_config = get_domain_config(request.domain)
388
- if "create_infill_prompt" not in domain_config:
389
- raise HTTPException(
390
- status_code=400,
391
- detail=f"Domain '{request.domain}' does not support infill operations"
392
- )
393
- create_infill_prompt = domain_config["create_infill_prompt"]
394
-
395
- # Process with each model (sequentially for memory safety)
396
- model_results = []
397
-
398
- for model_name in models_to_use:
399
- model_start = time.time()
400
- results = []
401
- error_count = 0
402
-
403
- for item in request.items:
404
- result = await process_infill_item(
405
- item=item,
406
- model_name=model_name,
407
- options=request.options,
408
- create_infill_prompt=create_infill_prompt
409
- )
410
- results.append(result)
411
- if result.status == "error":
412
- error_count += 1
413
-
414
- model_results.append(ModelInfillResult(
415
- model=model_name,
416
- type=MODEL_CONFIG[model_name]["type"],
417
- results=results,
418
- time=round(time.time() - model_start, 2),
419
- error_count=error_count
420
- ))
421
-
422
- return CompareInfillResponse(
423
- domain=request.domain,
424
- models=model_results,
425
- total_time=round(time.time() - total_start, 2)
426
- )
427
-
428
-
429
- async def process_infill_item(
430
- item,
431
- model_name: str,
432
- options,
433
- create_infill_prompt
434
- ) -> InfillResult:
435
- """
436
- Process a single infill item.
437
-
438
- Returns InfillResult with status, filled_text, and gaps.
439
- """
440
- try:
441
- # Normalize gaps to [GAP:n] format
442
- normalized_text, gaps = normalize_gaps_to_tagged(item.text_with_gaps)
443
-
444
- if not gaps:
445
- # No gaps found, return original text
446
- return InfillResult(
447
- id=item.id,
448
- status="ok",
449
- filled_text=item.text_with_gaps,
450
- gaps=[],
451
- error=None
452
- )
453
-
454
- # Build prompt
455
- if item.custom_messages:
456
- chat_messages = item.custom_messages
457
- use_grammar = False # Custom messages = plain text output expected
458
- else:
459
- chat_messages = create_infill_prompt(normalized_text, options, attributes=item.attributes)
460
- use_grammar = True # Standard prompt = use grammar for structured JSON
461
-
462
- # Generate with optional GBNF grammar constraint
463
- llm = await registry.get_model(model_name)
464
-
465
- grammar_str = None
466
- if use_grammar and hasattr(llm, 'llm') and llm.llm is not None:
467
- # Use model's default grammar (loaded from answers.gbnf) if available
468
- if hasattr(llm, 'default_grammar') and llm.default_grammar:
469
- grammar_str = llm.default_grammar
470
- print(f"DEBUG: Using model's default GBNF grammar", flush=True)
471
- else:
472
- # Fallback to dynamic grammar generation
473
- try:
474
- from app.logic.grammar_utils import get_infill_grammar
475
- grammar_str = get_infill_grammar(len(gaps))
476
- print(f"DEBUG: Using dynamic GBNF grammar for {len(gaps)} gaps", flush=True)
477
- except ImportError:
478
- pass
479
-
480
- raw_output = await llm.generate(
481
- chat_messages=chat_messages,
482
- max_new_tokens=options.max_new_tokens,
483
- temperature=0.3 if use_grammar else options.temperature, # Lower temp with grammar
484
- top_p=0.9,
485
- grammar=grammar_str,
486
- )
487
-
488
- # If custom_messages were provided, the output is plain text (not JSON)
489
- # Just return it directly as a single gap fill
490
- if item.custom_messages:
491
- # Clean up the raw output - strip whitespace, quotes, etc.
492
- choice = raw_output.strip().strip('"\'.,').strip()
493
- return InfillResult(
494
- id=item.id,
495
- status="ok",
496
- filled_text=choice, # The filled text is just the choice itself
497
- gaps=[GapFill(index=1, marker="[GAP:1]", choice=choice, alternatives=[])],
498
- error=None
499
- )
500
-
501
- # Parse JSON from output (standard prompt format)
502
- parsed = parse_infill_response(raw_output)
503
-
504
- if not parsed:
505
- # JSON parsing failed
506
- return InfillResult(
507
- id=item.id,
508
- status="error",
509
- filled_text=None,
510
- gaps=[],
511
- error=f"Failed to parse JSON from model output: {raw_output[:200]}..."
512
- )
513
-
514
- # Extract gaps and build result
515
- gap_fills = []
516
- fills_dict = {}
517
-
518
- for gap_data in parsed.get("gaps", []):
519
- gap_fill = GapFill(
520
- index=gap_data.get("index", 0),
521
- marker=gap_data.get("marker", ""),
522
- choice=gap_data.get("choice", ""),
523
- alternatives=gap_data.get("alternatives", [])
524
- )
525
- gap_fills.append(gap_fill)
526
- fills_dict[gap_fill.index] = gap_fill.choice
527
-
528
- # Get filled text - prefer model's version, fallback to reconstruction
529
- filled_text = parsed.get("filled_text")
530
- if not filled_text and fills_dict:
531
- filled_text = apply_fills(normalized_text, gaps, fills_dict)
532
-
533
- return InfillResult(
534
- id=item.id,
535
- status="ok",
536
- filled_text=filled_text,
537
- gaps=gap_fills,
538
- error=None
539
- )
540
-
541
- except Exception as e:
542
- return InfillResult(
543
- id=item.id,
544
- status="error",
545
- filled_text=None,
546
- gaps=[],
547
- error=str(e)
548
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/main_simple.py DELETED
@@ -1,202 +0,0 @@
1
- import os
2
- import subprocess
3
- import sys
4
- from typing import Optional, List
5
- from fastapi import FastAPI, HTTPException
6
- from pydantic import BaseModel
7
-
8
- # Install llama-cpp-python with CUDA support at runtime
9
- try:
10
- import llama_cpp
11
- except ImportError:
12
- print("[STARTUP] Installing llama-cpp-python with CUDA...")
13
- result = subprocess.run(
14
- [sys.executable, "-m", "pip", "install", "--quiet", "--prefer-binary",
15
- "--index-url", "https://abetlen.github.io/llama-cpp-python/whl/cu121",
16
- "llama-cpp-python[server]>=0.3.16"],
17
- capture_output=True,
18
- text=True
19
- )
20
- if result.returncode != 0:
21
- print("[STARTUP] CUDA wheel failed, trying CPU fallback...")
22
- subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "llama-cpp-python>=0.3.16"], check=False)
23
-
24
- from app.models.registry import registry, MODEL_CONFIG
25
-
26
- # Request/Response Models
27
- class Message(BaseModel):
28
- role: str
29
- content: str
30
-
31
- class ChatRequest(BaseModel):
32
- model: str
33
- messages: List[Message]
34
- max_tokens: int = 150
35
- temperature: float = 0.7
36
- top_p: float = 0.9
37
-
38
- class ChatChoice(BaseModel):
39
- message: Message
40
- finish_reason: str
41
-
42
- class ChatResponse(BaseModel):
43
- model: str
44
- choices: List[ChatChoice]
45
- usage: dict
46
-
47
- class GenerateRequest(BaseModel):
48
- model: str
49
- prompt: str
50
- max_tokens: int = 150
51
- temperature: float = 0.7
52
- top_p: float = 0.9
53
-
54
- class GenerateResponse(BaseModel):
55
- model: str
56
- text: str
57
- tokens_generated: int
58
-
59
- class ModelInfo(BaseModel):
60
- name: str
61
- type: str
62
- device: str = "unknown"
63
-
64
- class ModelsResponse(BaseModel):
65
- models: List[ModelInfo]
66
-
67
- class HealthResponse(BaseModel):
68
- status: str
69
- gpu_available: bool
70
- models_available: int
71
-
72
- # Create app
73
- app = FastAPI(
74
- title="Bielik LLM Service",
75
- description="Pure inference service for Bielik models with GPU acceleration",
76
- version="2.0.0"
77
- )
78
-
79
- @app.on_event("startup")
80
- async def startup_event():
81
- """Initialize service on startup."""
82
- print("Application started. Models will be loaded lazily on first request.")
83
- print(f"Available models: {registry.get_available_model_names()}")
84
-
85
- try:
86
- import torch
87
- gpu_available = torch.cuda.is_available()
88
- gpu_name = torch.cuda.get_device_name(0) if gpu_available else "N/A"
89
- print(f"GPU available: {gpu_available}, Device: {gpu_name}")
90
- except ImportError:
91
- print("PyTorch not available for GPU check")
92
- except Exception as e:
93
- print(f"GPU check failed: {e}")
94
-
95
- @app.get("/health", response_model=HealthResponse)
96
- async def health_check():
97
- """Health check endpoint."""
98
- gpu_available = False
99
- try:
100
- import torch
101
- gpu_available = torch.cuda.is_available()
102
- except:
103
- pass
104
-
105
- return HealthResponse(
106
- status="ok",
107
- gpu_available=gpu_available,
108
- models_available=len(registry.get_available_model_names())
109
- )
110
-
111
- @app.get("/models", response_model=ModelsResponse)
112
- async def list_models():
113
- """List all available models."""
114
- models_list = []
115
- for model_name in registry.get_available_model_names():
116
- info = registry.get_model_info(model_name)
117
- models_list.append(ModelInfo(
118
- name=model_name,
119
- type=info.get("type", "unknown"),
120
- device=info.get("device", "unknown")
121
- ))
122
- return ModelsResponse(models=models_list)
123
-
124
- @app.post("/chat", response_model=ChatResponse)
125
- async def chat_completion(request: ChatRequest):
126
- """
127
- Chat completion endpoint (OpenAI compatible).
128
-
129
- Accepts a list of messages and returns a completion.
130
- """
131
- # Validate model
132
- if request.model not in registry.get_available_model_names():
133
- raise HTTPException(status_code=400, detail=f"Unknown model: {request.model}")
134
-
135
- try:
136
- # Load model
137
- llm = await registry.get_model(request.model)
138
-
139
- # Convert messages to list of dicts
140
- messages = [{"role": msg.role, "content": msg.content} for msg in request.messages]
141
-
142
- # Generate
143
- output = await llm.generate(
144
- chat_messages=messages,
145
- max_new_tokens=request.max_tokens,
146
- temperature=request.temperature,
147
- top_p=request.top_p,
148
- )
149
-
150
- return ChatResponse(
151
- model=request.model,
152
- choices=[ChatChoice(
153
- message=Message(role="assistant", content=output),
154
- finish_reason="stop"
155
- )],
156
- usage={
157
- "prompt_tokens": sum(len(msg.get("content", "").split()) for msg in messages),
158
- "completion_tokens": len(output.split())
159
- }
160
- )
161
- except Exception as e:
162
- raise HTTPException(status_code=500, detail=f"Generation error: {str(e)}")
163
-
164
- @app.post("/generate", response_model=GenerateResponse)
165
- async def generate_text(request: GenerateRequest):
166
- """
167
- Raw text generation endpoint.
168
-
169
- Accepts a prompt string and returns generated text.
170
- """
171
- # Validate model
172
- if request.model not in registry.get_available_model_names():
173
- raise HTTPException(status_code=400, detail=f"Unknown model: {request.model}")
174
-
175
- try:
176
- # Load model
177
- llm = await registry.get_model(request.model)
178
-
179
- # Generate
180
- output = await llm.generate(
181
- prompt=request.prompt,
182
- max_new_tokens=request.max_tokens,
183
- temperature=request.temperature,
184
- top_p=request.top_p,
185
- )
186
-
187
- return GenerateResponse(
188
- model=request.model,
189
- text=output,
190
- tokens_generated=len(output.split())
191
- )
192
- except Exception as e:
193
- raise HTTPException(status_code=500, detail=f"Generation error: {str(e)}")
194
-
195
- @app.get("/")
196
- async def root():
197
- """Root endpoint."""
198
- return {
199
- "message": "Bielik LLM Service",
200
- "docs": "/docs",
201
- "endpoints": ["/chat", "/generate", "/models", "/health"]
202
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/__init__.py DELETED
@@ -1,16 +0,0 @@
1
- """
2
- Models module - LLM implementations and registry.
3
- """
4
-
5
- from app.models.base_llm import BaseLLM
6
- from app.models.huggingface_local import HuggingFaceLocal
7
- from app.models.huggingface_inference_api import HuggingFaceInferenceAPI
8
- from app.models.registry import registry, MODEL_CONFIG
9
-
10
- __all__ = [
11
- "BaseLLM",
12
- "HuggingFaceLocal",
13
- "HuggingFaceInferenceAPI",
14
- "registry",
15
- "MODEL_CONFIG",
16
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/base_llm.py DELETED
@@ -1,54 +0,0 @@
1
- """
2
- Abstract base class for all LLM implementations.
3
- """
4
-
5
- from abc import ABC, abstractmethod
6
- from typing import Optional, List, Dict, Any
7
-
8
-
9
- class BaseLLM(ABC):
10
- """Abstract interface for LLM models."""
11
-
12
- def __init__(self, name: str, model_id: str):
13
- self.name = name
14
- self.model_id = model_id
15
- self._initialized = False
16
-
17
- @property
18
- def is_initialized(self) -> bool:
19
- return self._initialized
20
-
21
- @abstractmethod
22
- async def initialize(self) -> None:
23
- """Initialize the model. Must be called before generate()."""
24
- pass
25
-
26
- @abstractmethod
27
- async def generate(
28
- self,
29
- prompt: str = None,
30
- chat_messages: List[Dict[str, str]] = None,
31
- max_new_tokens: int = 150,
32
- temperature: float = 0.7,
33
- top_p: float = 0.9,
34
- **kwargs
35
- ) -> str:
36
- """
37
- Generate text from prompt or chat messages.
38
-
39
- Args:
40
- prompt: Raw text prompt
41
- chat_messages: List of {"role": "...", "content": "..."} messages
42
- max_new_tokens: Maximum tokens to generate
43
- temperature: Sampling temperature
44
- top_p: Nucleus sampling parameter
45
-
46
- Returns:
47
- Generated text string
48
- """
49
- pass
50
-
51
- @abstractmethod
52
- def get_info(self) -> Dict[str, Any]:
53
- """Return model information for /models endpoint."""
54
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/huggingface_inference_api.py DELETED
@@ -1,127 +0,0 @@
1
- """
2
- HuggingFace Inference API Model - Cloud-based inference.
3
- Uses HuggingFace's serverless Inference API for models that are too large to run locally.
4
- """
5
-
6
- import os
7
- import asyncio
8
- from typing import List, Dict, Any, Optional
9
- from app.models.base_llm import BaseLLM
10
-
11
- try:
12
- from huggingface_hub import InferenceClient
13
- HAS_HF_HUB = True
14
- except ImportError:
15
- HAS_HF_HUB = False
16
- InferenceClient = None
17
-
18
-
19
- class HuggingFaceInferenceAPI(BaseLLM):
20
- """
21
- Wrapper for HuggingFace Inference API.
22
- Runs models on HuggingFace's cloud servers - no local GPU/memory needed.
23
- """
24
-
25
- def __init__(self, name: str, model_id: str):
26
- super().__init__(name, model_id)
27
- self.client = None
28
- self._response_cache = {}
29
- self._max_cache_size = 100
30
-
31
- if not HAS_HF_HUB:
32
- raise ImportError("huggingface_hub is not installed. Run: pip install huggingface_hub")
33
-
34
- async def initialize(self) -> None:
35
- """Initialize the Inference API client."""
36
- if self._initialized:
37
- return
38
-
39
- try:
40
- token = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_TOKEN")
41
-
42
- if not token:
43
- print(f"[{self.name}] Warning: No HF_TOKEN found. Some models may require authentication.")
44
-
45
- self.client = InferenceClient(
46
- model=self.model_id,
47
- token=token
48
- )
49
-
50
- self._initialized = True
51
- print(f"[{self.name}] Inference API client initialized for: {self.model_id}")
52
-
53
- except Exception as e:
54
- print(f"[{self.name}] Failed to initialize Inference API: {e}")
55
- raise RuntimeError(f"Failed to initialize Inference API: {e}") from e
56
-
57
- async def generate(
58
- self,
59
- prompt: str = None,
60
- chat_messages: List[Dict[str, str]] = None,
61
- max_new_tokens: int = 150,
62
- temperature: float = 0.7,
63
- top_p: float = 0.9,
64
- **kwargs
65
- ) -> str:
66
- """Generate text using HuggingFace Inference API."""
67
-
68
- if not self._initialized or self.client is None:
69
- raise RuntimeError(f"[{self.name}] Client not initialized")
70
-
71
- # Ensure we have messages
72
- messages = chat_messages
73
- if not messages and prompt:
74
- messages = [{"role": "user", "content": prompt}]
75
-
76
- if not messages:
77
- raise ValueError("Either prompt or chat_messages required")
78
-
79
- # Cache check
80
- import json
81
- cache_key = f"{json.dumps(messages)}_{max_new_tokens}_{temperature}_{top_p}"
82
- if cache_key in self._response_cache:
83
- return self._response_cache[cache_key]
84
-
85
- print(f"[{self.name}] Calling Inference API with {len(messages)} messages", flush=True)
86
-
87
- try:
88
- # Use chat_completion method (huggingface_hub InferenceClient)
89
- response = await asyncio.to_thread(
90
- self.client.chat_completion,
91
- messages=messages,
92
- max_tokens=max_new_tokens,
93
- temperature=temperature,
94
- top_p=top_p,
95
- )
96
-
97
- response_text = response.choices[0].message.content.strip()
98
- print(f"[{self.name}] Inference API response: {response_text[:100]}...", flush=True)
99
-
100
- # Cache store
101
- if len(self._response_cache) >= self._max_cache_size:
102
- first_key = next(iter(self._response_cache))
103
- del self._response_cache[first_key]
104
- self._response_cache[cache_key] = response_text
105
-
106
- return response_text
107
-
108
- except Exception as e:
109
- print(f"[{self.name}] Inference API error: {e}", flush=True)
110
- raise RuntimeError(f"Inference API call failed: {e}") from e
111
-
112
- def get_info(self) -> Dict[str, Any]:
113
- """Return model information for /models endpoint."""
114
- return {
115
- "name": self.name,
116
- "model_id": self.model_id,
117
- "type": "inference_api",
118
- "backend": "HuggingFace Inference API",
119
- "loaded": self._initialized,
120
- "cloud_based": True
121
- }
122
-
123
- async def cleanup(self) -> None:
124
- """Cleanup resources."""
125
- self.client = None
126
- self._initialized = False
127
- print(f"[{self.name}] Inference API client cleaned up")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/huggingface_local.py DELETED
@@ -1,289 +0,0 @@
1
- """
2
- Local HuggingFace model implementation using transformers pipeline.
3
-
4
- Optimizations:
5
- - KV Cache: Enabled by default (5-10x speedup on GPU, 1.5x on CPU)
6
- - Flash Attention: Used when available (GPU only)
7
- - 8-Bit Quantization: Optional for CPU environments (4-6x speedup, 50% memory reduction)
8
- """
9
-
10
- from typing import List, Dict, Any, Optional
11
- from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
12
- import torch
13
- import asyncio
14
- import os
15
-
16
- from app.models.base_llm import BaseLLM
17
-
18
- # Try to import bitsandbytes, but don't fail if not available
19
- try:
20
- from transformers import BitsAndBytesConfig
21
- HAS_BITSANDBYTES = True
22
- except ImportError:
23
- HAS_BITSANDBYTES = False
24
- print("[WARNING] bitsandbytes not available - 8-bit quantization disabled")
25
-
26
-
27
- class HuggingFaceLocal(BaseLLM):
28
- """
29
- Local HuggingFace model loaded into container memory.
30
- Best for smaller models (< 3B parameters) that fit in RAM.
31
-
32
- Features:
33
- - KV caching enabled (1.5-2x faster on CPU, 5-10x on GPU)
34
- - Flash Attention v2 support (GPU only)
35
- - 8-bit quantization for CPU (via bitsandbytes if available) or Dynamic Quantization (torch)
36
- - Mixed precision (float16 or bfloat16 when possible)
37
- - Response Caching (LRU)
38
- """
39
-
40
- def __init__(self, name: str, model_id: str, device: str = "cpu", use_cache: bool = True, use_8bit: bool = False):
41
- super().__init__(name, model_id)
42
- self.device = device
43
- self.pipeline = None
44
- self.tokenizer = None
45
- self.model = None
46
- self.use_cache = use_cache
47
- self._response_cache = {} # Simple dict cache
48
- self._max_cache_size = 100
49
-
50
- # Only enable 8-bit if explicitly requested (opt-in, not by default)
51
- # Default to False since bitsandbytes may not be available in all deployment environments
52
- requested_8bit = use_8bit or (device == "cpu" and os.getenv("USE_8BIT_QUANTIZATION", "false").lower() == "true")
53
- self.use_8bit = requested_8bit and HAS_BITSANDBYTES
54
-
55
- if requested_8bit and not HAS_BITSANDBYTES:
56
- print(f"[{name}] 8-bit quantization requested but bitsandbytes not installed - falling back to full precision")
57
-
58
- self.use_flash_attention = os.getenv("USE_FLASH_ATTENTION", "true").lower() == "true"
59
-
60
- # Determine device index and dtype
61
- if device == "cuda" and torch.cuda.is_available():
62
- self.device_index = 0
63
- # Try to use bfloat16 on modern GPUs, else float16
64
- self.torch_dtype = torch.bfloat16 if torch.cuda.is_available() and hasattr(torch.cuda, "get_device_capability") else torch.float16
65
- else:
66
- self.device_index = -1 # CPU
67
- self.torch_dtype = torch.float32
68
-
69
- async def initialize(self) -> None:
70
- """Load model into memory with optimizations."""
71
- if self._initialized:
72
- return
73
-
74
- try:
75
- print(f"[{self.name}] Loading local model: {self.model_id}")
76
- print(f"[{self.name}] Device: {self.device} | Dtype: {self.torch_dtype} | KV Cache: {self.use_cache} | 8-bit: {self.use_8bit}")
77
-
78
- self.tokenizer = await asyncio.to_thread(
79
- AutoTokenizer.from_pretrained,
80
- self.model_id,
81
- trust_remote_code=True
82
- )
83
-
84
- # Model config optimizations
85
- model_kwargs = {
86
- "trust_remote_code": True,
87
- }
88
-
89
- # Add 8-bit quantization for CPU (4-6x faster, 50% less memory)
90
- if self.use_8bit and HAS_BITSANDBYTES:
91
- try:
92
- print(f"[{self.name}] Using 8-bit quantization for CPU optimization")
93
- bnb_config = BitsAndBytesConfig(
94
- load_in_8bit=True,
95
- bnb_8bit_compute_dtype=torch.float16,
96
- bnb_8bit_use_double_quant=True,
97
- )
98
- model_kwargs["quantization_config"] = bnb_config
99
- model_kwargs["device_map"] = "cpu"
100
- except Exception as e:
101
- print(f"[{self.name}] Failed to setup 8-bit quantization: {e}")
102
- print(f"[{self.name}] Falling back to full precision")
103
- self.use_8bit = False
104
- model_kwargs["torch_dtype"] = self.torch_dtype
105
- model_kwargs["device_map"] = "cpu"
106
-
107
- # Standard loading without quantization
108
- if not self.use_8bit:
109
- model_kwargs["torch_dtype"] = self.torch_dtype
110
- model_kwargs["device_map"] = self.device if self.device == "cuda" else "cpu"
111
-
112
- # Enable flash attention if requested and available (GPU only)
113
- if self.use_flash_attention and self.device == "cuda" and not self.use_8bit:
114
- model_kwargs["attn_implementation"] = "flash_attention_2"
115
-
116
- self.model = await asyncio.to_thread(
117
- AutoModelForCausalLM.from_pretrained,
118
- self.model_id,
119
- **model_kwargs
120
- )
121
-
122
- # --- CPU DYNAMIC QUANTIZATION ---
123
- if self.device == "cpu" and not self.use_8bit:
124
- try:
125
- print(f"[{self.name}] Applying dynamic quantization for CPU optimization...")
126
- self.model = torch.quantization.quantize_dynamic(
127
- self.model, {torch.nn.Linear}, dtype=torch.qint8
128
- )
129
- print(f"[{self.name}] Dynamic quantization applied.")
130
- except Exception as e:
131
- print(f"[{self.name}] Dynamic quantization failed: {e}")
132
-
133
- # Ensure cache is enabled on model config
134
- if hasattr(self.model.config, 'use_cache'):
135
- self.model.config.use_cache = self.use_cache
136
-
137
- self._initialized = True
138
- print(f"[{self.name}] Model loaded successfully (use_cache={self.use_cache})")
139
-
140
- except Exception as e:
141
- print(f"[{self.name}] Failed to load model: {e}")
142
- raise
143
-
144
- async def generate(
145
- self,
146
- prompt: str = None,
147
- chat_messages: List[Dict[str, str]] = None,
148
- max_new_tokens: int = 150,
149
- temperature: float = 0.7,
150
- top_p: float = 0.9,
151
- **kwargs
152
- ) -> str:
153
- """
154
- Generate text using direct model.generate() with proper KV caching.
155
-
156
- KV Cache Impact (with proper implementation):
157
- - WITH: ~9 seconds for 10 ads (50 gaps)
158
- - WITHOUT: ~42 seconds (4.7x slower)
159
- """
160
-
161
- if not self._initialized or self.model is None:
162
- raise RuntimeError(f"[{self.name}] Model not initialized")
163
-
164
- formatted_prompt = None
165
-
166
- # Format prompt from chat messages
167
- if chat_messages:
168
- try:
169
- formatted_prompt = self.tokenizer.apply_chat_template(
170
- chat_messages,
171
- tokenize=False,
172
- add_generation_prompt=True
173
- )
174
- except Exception as e:
175
- print(f"[{self.name}] apply_chat_template failed: {e}, using fallback")
176
- formatted_prompt = self._format_chat_fallback(chat_messages)
177
-
178
- # Use raw prompt if provided
179
- if formatted_prompt is None and prompt:
180
- formatted_prompt = prompt
181
-
182
- if formatted_prompt is None:
183
- raise ValueError("Either prompt or chat_messages required")
184
-
185
- # --- CACHE CHECK ---
186
- cache_key = f"{formatted_prompt}_{max_new_tokens}_{temperature}_{top_p}"
187
- if cache_key in self._response_cache:
188
- # print(f"[{self.name}] Cache hit!")
189
- return self._response_cache[cache_key]
190
-
191
- # Tokenize input
192
- inputs = await asyncio.to_thread(
193
- self.tokenizer.encode,
194
- formatted_prompt,
195
- return_tensors="pt"
196
- )
197
-
198
- # Move to device
199
- if self.device == "cuda":
200
- inputs = await asyncio.to_thread(lambda: inputs.to("cuda"))
201
-
202
- # Generate with explicit KV cache
203
- outputs = await asyncio.to_thread(
204
- self.model.generate,
205
- inputs,
206
- max_new_tokens=max_new_tokens,
207
- do_sample=True,
208
- temperature=temperature,
209
- top_p=top_p,
210
- use_cache=True, # CRITICAL: Enable KV cache
211
- eos_token_id=self.tokenizer.eos_token_id,
212
- pad_token_id=self.tokenizer.eos_token_id if self.tokenizer.pad_token_id is None else self.tokenizer.pad_token_id,
213
- )
214
-
215
- # Decode output
216
- output_text = await asyncio.to_thread(
217
- self.tokenizer.decode,
218
- outputs[0],
219
- skip_special_tokens=True
220
- )
221
-
222
- # Remove prompt from output
223
- if output_text.startswith(formatted_prompt):
224
- response = output_text[len(formatted_prompt):]
225
- else:
226
- response = output_text
227
-
228
- # Clean up special tokens
229
- for token in ["<|im_end|>", "<end_of_turn>", "<eos>", "</s>"]:
230
- if response.endswith(token):
231
- response = response[:-len(token)]
232
-
233
- result = response.strip()
234
-
235
- # --- CACHE STORE ---
236
- if len(self._response_cache) >= self._max_cache_size:
237
- # Remove oldest item (approximate LRU by iterating once)
238
- first_key = next(iter(self._response_cache))
239
- del self._response_cache[first_key]
240
- self._response_cache[cache_key] = result
241
-
242
- return result
243
-
244
- def _format_chat_fallback(self, chat_messages: List[Dict[str, str]]) -> str:
245
- """
246
- Fallback chat formatting for models without proper chat template.
247
- Works with Gemma and other models.
248
- """
249
- formatted = ""
250
- for msg in chat_messages:
251
- role = msg.get("role", "user")
252
- content = msg.get("content", "")
253
-
254
- if role == "system":
255
- formatted += f"{content}\n\n"
256
- elif role == "user":
257
- formatted += f"User: {content}\n"
258
- elif role == "assistant":
259
- formatted += f"Assistant: {content}\n"
260
-
261
- # Add generation prompt
262
- formatted += "Assistant:"
263
- return formatted
264
-
265
- def get_info(self) -> Dict[str, Any]:
266
- """Return model info."""
267
- return {
268
- "name": self.name,
269
- "model_id": self.model_id,
270
- "type": "local",
271
- "initialized": self._initialized,
272
- "device": self.device
273
- }
274
-
275
- async def cleanup(self) -> None:
276
- """Release model from memory."""
277
- if self.pipeline is not None:
278
- del self.pipeline
279
- self.pipeline = None
280
- if self.tokenizer is not None:
281
- del self.tokenizer
282
- self.tokenizer = None
283
- self._initialized = False
284
-
285
- # Force CUDA cache clear if available
286
- if torch.cuda.is_available():
287
- torch.cuda.empty_cache()
288
-
289
- print(f"[{self.name}] Model unloaded from memory")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/huggingface_service.py DELETED
@@ -1,111 +0,0 @@
1
- from transformers import pipeline, AutoTokenizer
2
- import torch
3
- from fastapi import HTTPException
4
- import asyncio
5
-
6
- class HuggingFaceTextGenerationService:
7
- def __init__(self, model_name_or_path: str, device: str = None, task: str = "text-generation"):
8
- self.model_name_or_path = model_name_or_path
9
- self.task = task
10
- self.pipeline = None
11
- self.tokenizer = None
12
-
13
- if device is None:
14
- self.device_index = 0 if torch.cuda.is_available() else -1
15
- elif device == "cuda" and torch.cuda.is_available():
16
- self.device_index = 0
17
- elif device == "cpu":
18
- self.device_index = -1
19
- else:
20
- self.device_index = -1
21
-
22
- if self.device_index == 0:
23
- print("CUDA (GPU) is available. Using GPU.")
24
- else:
25
- print(f"Device set to use {'cpu' if self.device_index == -1 else f'cuda:{self.device_index}'}")
26
-
27
-
28
- async def initialize(self):
29
- try:
30
- print(f"Initializing Hugging Face pipeline for model: {self.model_name_or_path} on device index: {self.device_index}")
31
- self.tokenizer = await asyncio.to_thread(
32
- AutoTokenizer.from_pretrained, self.model_name_or_path, trust_remote_code=True
33
- )
34
- self.pipeline = await asyncio.to_thread(
35
- pipeline,
36
- self.task,
37
- model=self.model_name_or_path,
38
- tokenizer=self.tokenizer,
39
- device=self.device_index,
40
- torch_dtype=torch.bfloat16 if self.device_index != -1 and torch.cuda.is_available() and torch.cuda.is_bf16_supported() else torch.float32,
41
- trust_remote_code=True,
42
- )
43
- print(f"Pipeline for model {self.model_name_or_path} initialized successfully.")
44
- except Exception as e:
45
- print(f"Error initializing HuggingFace pipeline: {e}")
46
- raise HTTPException(status_code=503, detail=f"LLM (HuggingFace) model could not be loaded: {str(e)}")
47
-
48
- async def generate_text(self, prompt_text: str = None, chat_template_messages: list = None, max_new_tokens: int = 250, temperature: float = 0.7, top_p: float = 0.9, do_sample: bool = True, **kwargs) -> str:
49
- if not self.pipeline or not self.tokenizer:
50
- raise Exception("Pipeline is not initialized. Call initialize() first.")
51
-
52
- formatted_prompt_input = ""
53
- if chat_template_messages:
54
- try:
55
- formatted_prompt_input = self.tokenizer.apply_chat_template(
56
- chat_template_messages,
57
- tokenize=False,
58
- add_generation_prompt=True
59
- )
60
- except Exception as e:
61
- print(f"Could not apply chat template, falling back to raw prompt if available. Error: {e}")
62
- if prompt_text:
63
- formatted_prompt_input = prompt_text
64
- else:
65
- raise ValueError("Cannot generate text without a valid prompt or chat_template_messages.")
66
- elif prompt_text:
67
- formatted_prompt_input = prompt_text
68
- else:
69
- raise ValueError("Either prompt_text or chat_template_messages must be provided.")
70
-
71
- try:
72
- generated_outputs = await asyncio.to_thread(
73
- self.pipeline,
74
- formatted_prompt_input,
75
- max_new_tokens=max_new_tokens,
76
- do_sample=do_sample,
77
- temperature=temperature,
78
- top_p=top_p,
79
- eos_token_id=self.tokenizer.eos_token_id,
80
- pad_token_id=self.tokenizer.eos_token_id if self.tokenizer.pad_token_id is None else self.tokenizer.pad_token_id, # Common setting
81
- **kwargs
82
- )
83
-
84
- if generated_outputs and isinstance(generated_outputs, list) and "generated_text" in generated_outputs[0]:
85
- full_generated_sequence = generated_outputs[0]["generated_text"]
86
-
87
- assistant_response = ""
88
- if full_generated_sequence.startswith(formatted_prompt_input):
89
- assistant_response = full_generated_sequence[len(formatted_prompt_input):]
90
- else:
91
- assistant_marker = "<|im_start|>assistant\n"
92
- last_marker_pos = full_generated_sequence.rfind(assistant_marker)
93
- if last_marker_pos != -1:
94
- assistant_response = full_generated_sequence[last_marker_pos + len(assistant_marker):]
95
- print("Warning: Used fallback parsing for assistant response.")
96
- else:
97
- print("Error: Could not isolate assistant response from the full generated sequence.")
98
- assistant_response = full_generated_sequence
99
-
100
- if assistant_response.endswith("<|im_end|>"):
101
- assistant_response = assistant_response[:-len("<|im_end|>")]
102
-
103
- return assistant_response.strip()
104
- else:
105
- print(f"Unexpected output format from pipeline: {generated_outputs}")
106
- return "Error: Could not parse generated text from pipeline output."
107
-
108
- except Exception as e:
109
- print(f"Error during text generation with {self.model_name_or_path}: {e}")
110
- raise HTTPException(status_code=500, detail=f"Error generating text: {str(e)}")
111
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/llama_cpp_model.py DELETED
@@ -1,180 +0,0 @@
1
- """
2
- GGUF Model implementation using llama-cpp-python.
3
- Highly optimized for CPU inference.
4
- """
5
-
6
- import os
7
- import asyncio
8
- import traceback
9
- from typing import List, Dict, Any, Optional
10
- from app.models.base_llm import BaseLLM
11
-
12
- try:
13
- from llama_cpp import Llama, LlamaGrammar
14
- HAS_LLAMA_CPP = True
15
- except ImportError:
16
- HAS_LLAMA_CPP = False
17
- LlamaGrammar = None
18
-
19
-
20
- class LlamaCppModel(BaseLLM):
21
- """
22
- Wrapper for GGUF models using llama.cpp.
23
- Provides significant speedups on CPU compared to Transformers.
24
- """
25
-
26
- def __init__(self, name: str, model_id: str, model_path: str = None, n_ctx: int = 4096, grammar_path: str = None, n_gpu_layers: int = -1):
27
- super().__init__(name, model_id)
28
- self.model_path = model_path
29
- self.n_ctx = n_ctx
30
- self.grammar_path = grammar_path
31
- self.n_gpu_layers = n_gpu_layers
32
- self.default_grammar = None # Will be loaded from file if provided
33
- self.llm = None
34
- self._response_cache = {}
35
- self._max_cache_size = 100
36
-
37
- if not HAS_LLAMA_CPP:
38
- raise ImportError("llama-cpp-python is not installed. Cannot use GGUF models.")
39
-
40
- async def initialize(self) -> None:
41
- """Load GGUF model."""
42
- if self._initialized:
43
- return
44
-
45
- if not self.model_path or not os.path.exists(self.model_path):
46
- # If exact path isn't provided, try to find it in the model directory
47
- # logic handled in registry usually, but safety check here
48
- raise FileNotFoundError(f"GGUF model file not found at: {self.model_path}")
49
-
50
- try:
51
- print(f"[{self.name}] Loading GGUF model from: {self.model_path}")
52
- print(f"[{self.name}] File size: {os.path.getsize(self.model_path) / (1024*1024):.2f} MB")
53
- print(f"[{self.name}] n_ctx={self.n_ctx}, n_threads={os.cpu_count()}, n_gpu_layers={self.n_gpu_layers}")
54
-
55
- # Load model in a thread to avoid blocking event loop
56
- # Enable verbose to see llama.cpp errors
57
- self.llm = await asyncio.to_thread(
58
- Llama,
59
- model_path=self.model_path,
60
- n_ctx=self.n_ctx,
61
- n_threads=os.cpu_count(), # Use all available cores
62
- n_gpu_layers=self.n_gpu_layers, # GPU layer offloading
63
- verbose=True # Enable verbose to see loading errors
64
- )
65
-
66
- self._initialized = True
67
- print(f"[{self.name}] GGUF Model loaded successfully (n_ctx={self.n_ctx}, n_gpu_layers={self.n_gpu_layers})")
68
-
69
- # Load grammar file if provided
70
- if self.grammar_path:
71
- grammar_full_path = os.path.join(os.path.dirname(__file__), "..", "logic", self.grammar_path)
72
- if os.path.exists(grammar_full_path):
73
- with open(grammar_full_path, 'r', encoding='utf-8') as f:
74
- self.default_grammar = f.read()
75
- print(f"[{self.name}] Loaded grammar from: {grammar_full_path}")
76
- else:
77
- print(f"[{self.name}] Grammar file not found: {grammar_full_path}")
78
-
79
- except Exception as e:
80
- error_msg = str(e) if str(e) else repr(e)
81
- print(f"[{self.name}] Failed to load GGUF model: {error_msg}")
82
- print(f"[{self.name}] Full traceback:")
83
- traceback.print_exc()
84
- raise RuntimeError(f"Failed to load GGUF model: {error_msg}") from e
85
-
86
- async def generate(
87
- self,
88
- prompt: str = None,
89
- chat_messages: List[Dict[str, str]] = None,
90
- max_new_tokens: int = 150,
91
- temperature: float = 0.7,
92
- top_p: float = 0.9,
93
- grammar: str = None,
94
- **kwargs
95
- ) -> str:
96
- """Generate text using llama.cpp
97
-
98
- Args:
99
- prompt: Simple text prompt (converted to user message)
100
- chat_messages: List of chat messages with role/content
101
- max_new_tokens: Maximum tokens to generate
102
- temperature: Sampling temperature (lower = more deterministic)
103
- top_p: Nucleus sampling threshold
104
- grammar: Optional GBNF grammar string to constrain output
105
- """
106
-
107
- if not self._initialized or self.llm is None:
108
- raise RuntimeError(f"[{self.name}] Model not initialized")
109
-
110
- # Ensure we have a list of messages
111
- messages = chat_messages
112
- if not messages and prompt:
113
- messages = [{"role": "user", "content": prompt}]
114
-
115
- if not messages:
116
- raise ValueError("Either prompt or chat_messages required")
117
-
118
- # Cache Check - using stringified messages for the key
119
- import json
120
- cache_key = f"{json.dumps(messages)}_{max_new_tokens}_{temperature}_{top_p}_{grammar is not None}"
121
- if cache_key in self._response_cache:
122
- return self._response_cache[cache_key]
123
-
124
- print(f"DEBUG: Generating with messages: {messages}", flush=True)
125
- if grammar:
126
- print(f"DEBUG: Using GBNF grammar constraint", flush=True)
127
-
128
- # Prepare grammar object if provided
129
- llama_grammar = None
130
- if grammar and LlamaGrammar:
131
- try:
132
- llama_grammar = LlamaGrammar.from_string(grammar)
133
- except Exception as e:
134
- print(f"DEBUG: Failed to parse grammar: {e}", flush=True)
135
- llama_grammar = None
136
-
137
- # Generate using chat completion to leverage internal templates
138
- output = await asyncio.to_thread(
139
- self.llm.create_chat_completion,
140
- messages=messages,
141
- max_tokens=max_new_tokens,
142
- temperature=temperature,
143
- top_p=top_p,
144
- grammar=llama_grammar,
145
- )
146
-
147
- print(f"DEBUG: Raw output object: {output}", flush=True)
148
-
149
- response_text = output['choices'][0]['message']['content'].strip()
150
- print(f"DEBUG: Extracted text: {response_text}", flush=True)
151
-
152
- # Cache Store
153
- if len(self._response_cache) >= self._max_cache_size:
154
- first_key = next(iter(self._response_cache))
155
- del self._response_cache[first_key]
156
- self._response_cache[cache_key] = response_text
157
-
158
- return response_text
159
-
160
- def get_info(self) -> Dict[str, Any]:
161
- """Return model information for /models endpoint."""
162
- return {
163
- "name": self.name,
164
- "model_id": self.model_id,
165
- "type": "gguf",
166
- "backend": "llama.cpp",
167
- "context_length": self.n_ctx,
168
- "loaded": self._initialized,
169
- "model_path": self.model_path,
170
- "has_grammar": self.default_grammar is not None,
171
- "gpu_layers": self.n_gpu_layers
172
- }
173
-
174
- async def cleanup(self) -> None:
175
- """Free memory."""
176
- if self.llm:
177
- del self.llm
178
- self.llm = None
179
- self._initialized = False
180
- print(f"[{self.name}] GGUF Model unloaded")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/registry.py DELETED
@@ -1,148 +0,0 @@
1
- """
2
- Model Registry - Central configuration and factory for all LLM models.
3
- """
4
-
5
- import os
6
- import gc
7
- from typing import Dict, List, Any, Optional
8
-
9
- from app.models.base_llm import BaseLLM
10
- from app.models.huggingface_inference_api import HuggingFaceInferenceAPI
11
- from app.models.transformers_model import TransformersModel
12
-
13
- # Model configuration
14
- MODEL_CONFIG = {
15
- "bielik-1.5b-transformer": {
16
- "id": "speakleash/Bielik-1.5B-v3.0-Instruct",
17
- "type": "transformers",
18
- "size": "1.5B",
19
- "polish_support": "excellent",
20
- "use_8bit": False,
21
- "device_map": "auto"
22
- },
23
- "bielik-11b-transformer": {
24
- "id": "speakleash/Bielik-11B-v2.3-Instruct",
25
- "type": "transformers",
26
- "size": "11B",
27
- "polish_support": "excellent",
28
- "use_8bit": True,
29
- "device_map": "auto",
30
- "enable_cpu_offload": True
31
- },
32
- "llama-3.1-8b": {
33
- "id": "meta-llama/Llama-3.1-8B-Instruct",
34
- "type": "inference_api",
35
- "polish_support": "good",
36
- "size": "8B",
37
- }
38
- }
39
-
40
- LOCAL_MODEL_BASE = os.getenv("MODEL_DIR", "/app/pretrain_model")
41
-
42
- class ModelRegistry:
43
- def __init__(self):
44
- self._models: Dict[str, BaseLLM] = {}
45
- self._config = MODEL_CONFIG.copy()
46
- self._active_local_model: Optional[str] = None
47
-
48
- def _create_model(self, name: str) -> BaseLLM:
49
- if name not in self._config:
50
- raise ValueError(f"Unknown model: {name}")
51
-
52
- config = self._config[name]
53
- model_type = config["type"]
54
- model_id = config["id"]
55
-
56
- if model_type == "transformers":
57
- use_8bit = config.get("use_8bit", True)
58
- device_map = config.get("device_map", "auto")
59
- enable_cpu_offload = config.get("enable_cpu_offload", False)
60
- return TransformersModel(
61
- name=name,
62
- model_id=model_id,
63
- use_8bit=use_8bit,
64
- device_map=device_map,
65
- enable_cpu_offload=enable_cpu_offload
66
- )
67
-
68
- elif model_type == "inference_api":
69
- return HuggingFaceInferenceAPI(name=name, model_id=model_id)
70
-
71
- else:
72
- raise ValueError(f"Unsupported model type: {model_type}")
73
-
74
- async def get_model(self, name: str) -> BaseLLM:
75
- config = self._config[name]
76
-
77
- # Unload previously active model to free GPU memory when switching models
78
- if self._active_local_model and self._active_local_model != name:
79
- print(f"Switching models: unloading '{self._active_local_model}' to load '{name}'")
80
- await self._unload_model(self._active_local_model)
81
-
82
- if name not in self._models:
83
- model = self._create_model(name)
84
- await model.initialize()
85
- self._models[name] = model
86
-
87
- self._active_local_model = name
88
- return self._models[name]
89
-
90
- async def _unload_model(self, name: str) -> None:
91
- if name in self._models:
92
- model = self._models[name]
93
- if hasattr(model, 'cleanup'): await model.cleanup()
94
- del self._models[name]
95
- gc.collect()
96
- print(f"Model '{name}' unloaded.")
97
-
98
- def get_model_info(self, name: str) -> Dict[str, Any]:
99
- config = self._config[name]
100
- return {
101
- "name": name,
102
- "model_id": config["id"],
103
- "type": config["type"],
104
- "size": config.get("size", "unknown"),
105
- "polish_support": config.get("polish_support", "unknown"),
106
- "loaded": name in self._models,
107
- "active": name == self._active_local_model
108
- }
109
-
110
- def get_available_model_names(self) -> List[str]:
111
- """Return list of all available model names."""
112
- return list(self._config.keys())
113
-
114
- def list_models(self) -> List[Dict[str, Any]]:
115
- """Return list of all models with their info."""
116
- return [self.get_model_info(name) for name in self._config.keys()]
117
-
118
- def get_loaded_models(self) -> List[str]:
119
- """Return list of currently loaded model names."""
120
- return list(self._models.keys())
121
-
122
- def get_active_model(self) -> Optional[str]:
123
- """Return name of currently active local model."""
124
- return self._active_local_model
125
-
126
- async def load_model(self, name: str) -> Dict[str, Any]:
127
- """Explicitly load a model and return its info."""
128
- await self.get_model(name)
129
- return self.get_model_info(name)
130
-
131
- async def unload_model(self, name: str) -> Dict[str, str]:
132
- """Explicitly unload a model and free its memory."""
133
- if name in self._models:
134
- await self._unload_model(name)
135
- if self._active_local_model == name:
136
- self._active_local_model = None
137
- return {"status": "success", "message": f"Model '{name}' unloaded"}
138
- return {"status": "error", "message": f"Model '{name}' not loaded"}
139
-
140
- async def unload_all_models(self) -> Dict[str, str]:
141
- """Unload all loaded models and free GPU memory."""
142
- loaded_models = list(self._models.keys())
143
- for model_name in loaded_models:
144
- await self._unload_model(model_name)
145
- self._active_local_model = None
146
- return {"status": "success", "message": f"Unloaded {len(loaded_models)} models"}
147
-
148
- registry = ModelRegistry()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/models/transformers_model.py DELETED
@@ -1,360 +0,0 @@
1
- """
2
- GPU-optimized Transformers implementation using bitsandbytes quantization.
3
- Automatically offloads to GPU if available, falls back to CPU gracefully.
4
- """
5
-
6
- import os
7
- import asyncio
8
- import traceback
9
- from typing import List, Dict, Any, Optional
10
- from app.models.base_llm import BaseLLM
11
-
12
- try:
13
- from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
14
- HAS_TRANSFORMERS = True
15
- except ImportError:
16
- HAS_TRANSFORMERS = False
17
-
18
- try:
19
- import bitsandbytes as bnb
20
- HAS_BITSANDBYTES = True
21
- except ImportError:
22
- HAS_BITSANDBYTES = False
23
-
24
- import torch
25
-
26
-
27
- class TransformersModel(BaseLLM):
28
- """
29
- Wrapper for HuggingFace Transformers models with GPU acceleration.
30
- Supports 8-bit quantization via bitsandbytes for memory efficiency.
31
- Automatically detects and uses GPU if available.
32
- """
33
-
34
- def __init__(self, name: str, model_id: str, use_8bit: bool = True, device_map: str = "auto", enable_cpu_offload: bool = False):
35
- super().__init__(name, model_id)
36
- self.use_8bit = use_8bit
37
- self.device_map = device_map
38
- env_cpu_offload = os.getenv("TRANSFORMERS_ENABLE_CPU_OFFLOAD", "").strip().lower() in ("1", "true", "yes", "on")
39
- self.enable_cpu_offload = enable_cpu_offload or env_cpu_offload
40
- self.offload_dir = os.getenv("HF_OFFLOAD_DIR", "/tmp/hf-offload")
41
- self.pipeline = None
42
- self.tokenizer = None
43
- self.model = None
44
- self._response_cache = {}
45
- self._max_cache_size = 100
46
-
47
- if not HAS_TRANSFORMERS:
48
- raise ImportError("transformers is not installed. Cannot use Transformers models.")
49
-
50
- async def initialize(self) -> None:
51
- """Load model with GPU optimization."""
52
- if self._initialized:
53
- return
54
-
55
- try:
56
- print(f"[{self.name}] Initializing Transformers model: {self.model_id}")
57
- print(f"[{self.name}] Device map: {self.device_map}, 8-bit quantization: {self.use_8bit}")
58
-
59
- # Load in thread to avoid blocking event loop
60
- await asyncio.to_thread(self._load_model)
61
-
62
- self._initialized = True
63
- print(f"[{self.name}] Transformers Model loaded successfully")
64
-
65
- except Exception as e:
66
- error_msg = str(e) if str(e) else repr(e)
67
- print(f"[{self.name}] Failed to load Transformers model: {error_msg}")
68
- traceback.print_exc()
69
- raise RuntimeError(f"Failed to load Transformers model: {error_msg}") from e
70
-
71
- def _load_model(self) -> None:
72
- """Load model with optimal device configuration and quantization support."""
73
- import gc
74
-
75
- # Set PyTorch environment variables for optimal memory management
76
- if not os.getenv("PYTORCH_CUDA_ALLOC_CONF"):
77
- os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
78
- print(f"[{self.name}] Set PYTORCH_CUDA_ALLOC_CONF to prevent GPU memory fragmentation")
79
-
80
- # Force garbage collection before loading new model
81
- gc.collect()
82
- if torch.cuda.is_available():
83
- torch.cuda.empty_cache()
84
-
85
- # Check GPU availability with detailed diagnostics
86
- cuda_available = torch.cuda.is_available()
87
- cuda_device_count = torch.cuda.device_count() if cuda_available else 0
88
- device = "cuda" if cuda_available else "cpu"
89
-
90
- print(f"[{self.name}] === MODEL LOADING DIAGNOSTICS ===")
91
- print(f"[{self.name}] torch.cuda.is_available(): {cuda_available}")
92
- print(f"[{self.name}] torch.cuda.device_count(): {cuda_device_count}")
93
- if cuda_available:
94
- try:
95
- print(f"[{self.name}] Current CUDA device: {torch.cuda.current_device()}")
96
- print(f"[{self.name}] CUDA device name: {torch.cuda.get_device_name(0)}")
97
- except:
98
- pass
99
- print(f"[{self.name}] ===================================")
100
- print(f"[{self.name}] Loading model: {self.model_id}")
101
- print(f"[{self.name}] Device to use: {device}")
102
- print(f"[{self.name}] Device map: {self.device_map}")
103
- print(f"[{self.name}] 8-bit quantization requested: {self.use_8bit}")
104
-
105
- # Load tokenizer
106
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
107
-
108
- # Use float16 for GPU, float32 for CPU
109
- dtype = torch.float16 if cuda_available else torch.float32
110
- is_large_model = "11b" in self.model_id.lower() or "11b" in self.name.lower()
111
- cpu_offload_enabled = self.enable_cpu_offload or is_large_model
112
-
113
- # Build model kwargs conditionally based on quantization setting
114
- model_kwargs = {
115
- "trust_remote_code": True,
116
- "torch_dtype": dtype,
117
- }
118
-
119
- # Apply 8-bit quantization if requested, available, and GPU is present
120
- if self.use_8bit and HAS_BITSANDBYTES and cuda_available:
121
- try:
122
- print(f"[{self.name}] Using 8-bit quantization for memory efficiency")
123
- bnb_config = BitsAndBytesConfig(
124
- load_in_8bit=True,
125
- bnb_8bit_compute_dtype=torch.float16,
126
- llm_int8_enable_fp32_cpu_offload=cpu_offload_enabled,
127
- )
128
- model_kwargs["quantization_config"] = bnb_config
129
- model_kwargs["device_map"] = "auto"
130
- if cpu_offload_enabled:
131
- os.makedirs(self.offload_dir, exist_ok=True)
132
- model_kwargs["offload_folder"] = self.offload_dir
133
- except Exception as e:
134
- print(f"[{self.name}] Failed to setup 8-bit quantization: {e}")
135
- print(f"[{self.name}] Falling back to full precision")
136
- self.use_8bit = False
137
- model_kwargs["device_map"] = self.device_map
138
- elif self.use_8bit and not cuda_available:
139
- # 8-bit quantization requested but no GPU available - fall back to full precision
140
- print(f"[{self.name}] WARNING: 8-bit quantization requested but no GPU available")
141
- print(f"[{self.name}] Falling back to full precision on CPU (model may be very slow)")
142
- self.use_8bit = False
143
- model_kwargs["device_map"] = "cpu"
144
- else:
145
- # No quantization - use explicit device mapping
146
- if not self.use_8bit and self.use_8bit is not None:
147
- print(f"[{self.name}] bitsandbytes not available or quantization disabled - using full precision")
148
-
149
- # For large models without quantization, be more careful with device mapping
150
- if "11b" in self.model_id.lower() and not self.use_8bit and cuda_available:
151
- print(f"[{self.name}] WARNING: Loading large 11B model without quantization on GPU")
152
- print(f"[{self.name}] WARNING: This may cause out-of-memory errors on 16GB GPUs")
153
- print(f"[{self.name}] WARNING: Consider enabling use_8bit=True in registry.py")
154
- # Use CPU offloading for safety
155
- model_kwargs["device_map"] = "cpu"
156
- else:
157
- model_kwargs["device_map"] = self.device_map
158
-
159
- try:
160
- self.model = AutoModelForCausalLM.from_pretrained(
161
- self.model_id,
162
- **model_kwargs
163
- )
164
- except ValueError as e:
165
- error_text = str(e)
166
- should_retry_with_offload = (
167
- self.use_8bit
168
- and HAS_BITSANDBYTES
169
- and cuda_available
170
- and "dispatched on the cpu or the disk" in error_text.lower()
171
- )
172
- if not should_retry_with_offload:
173
- raise
174
-
175
- print(f"[{self.name}] Retrying load with explicit fp32 CPU offload")
176
- os.makedirs(self.offload_dir, exist_ok=True)
177
-
178
- retry_kwargs = dict(model_kwargs)
179
- retry_kwargs["quantization_config"] = BitsAndBytesConfig(
180
- load_in_8bit=True,
181
- bnb_8bit_compute_dtype=torch.float16,
182
- llm_int8_enable_fp32_cpu_offload=True,
183
- )
184
- retry_kwargs["device_map"] = "auto"
185
- retry_kwargs["offload_folder"] = self.offload_dir
186
-
187
- try:
188
- total_mem = torch.cuda.get_device_properties(0).total_memory
189
- gpu_gib = max(1, int((total_mem / (1024 ** 3)) * 0.9))
190
- retry_kwargs["max_memory"] = {0: f"{gpu_gib}GiB", "cpu": "64GiB"}
191
- except Exception:
192
- pass
193
-
194
- self.model = AutoModelForCausalLM.from_pretrained(
195
- self.model_id,
196
- **retry_kwargs
197
- )
198
-
199
- # Log final state
200
- model_device = next(self.model.parameters()).device
201
- quantization_status = "8-bit quantized" if self.use_8bit else "full precision"
202
- print(f"[{self.name}] Model loaded successfully")
203
- print(f"[{self.name}] Dtype: {self.model.dtype} | Quantization: {quantization_status}")
204
- print(f"[{self.name}] Device: {model_device}")
205
-
206
- async def generate(
207
- self,
208
- prompt: str = None,
209
- chat_messages: List[Dict[str, str]] = None,
210
- max_new_tokens: int = 150,
211
- temperature: float = 0.7,
212
- top_p: float = 0.9,
213
- grammar: str = None,
214
- **kwargs
215
- ) -> str:
216
- """Generate text using Transformers pipeline.
217
-
218
- Note: grammar parameter is ignored (Transformers doesn't support GBNF).
219
- Use stricter prompt engineering instead.
220
- """
221
-
222
- if not self._initialized or self.model is None:
223
- raise RuntimeError(f"[{self.name}] Model not initialized")
224
-
225
- # Build prompt from messages
226
- prompt_text = self._build_prompt_from_messages(chat_messages) if chat_messages else prompt
227
-
228
- if not prompt_text:
229
- raise ValueError("Either prompt or chat_messages required")
230
-
231
- # Cache Check
232
- import json
233
- cache_key = f"{json.dumps(chat_messages or prompt_text)}_{max_new_tokens}_{temperature}_{top_p}"
234
- if cache_key in self._response_cache:
235
- return self._response_cache[cache_key]
236
-
237
- print(f"DEBUG: Generating with Transformers model", flush=True)
238
- if grammar:
239
- print(f"DEBUG: Note - GBNF grammar not supported in Transformers, using prompt engineering instead", flush=True)
240
-
241
- # Generate in thread to avoid blocking
242
- response_text = await asyncio.to_thread(
243
- self._generate_text,
244
- prompt_text,
245
- max_new_tokens,
246
- temperature,
247
- top_p
248
- )
249
-
250
- # Cache Store
251
- if len(self._response_cache) >= self._max_cache_size:
252
- first_key = next(iter(self._response_cache))
253
- del self._response_cache[first_key]
254
- self._response_cache[cache_key] = response_text
255
-
256
- print(f"DEBUG: Extracted text: {response_text[:200]}", flush=True)
257
- return response_text
258
-
259
- def _build_prompt_from_messages(self, messages: List[Dict[str, str]]) -> str:
260
- """Convert chat messages to prompt using Bielik's chat template."""
261
- # Bielik uses: <|im_start|>role\ncontent<|im_end|>\n
262
- prompt_parts = []
263
- for msg in messages:
264
- role = msg.get("role", "user")
265
- content = msg.get("content", "")
266
- prompt_parts.append(f"<|im_start|>{role}\n{content}<|im_end|>\n")
267
-
268
- # Add assistant start token for generation
269
- prompt_parts.append("<|im_start|>assistant\n")
270
- return "".join(prompt_parts)
271
-
272
- def _generate_text(
273
- self,
274
- prompt: str,
275
- max_new_tokens: int,
276
- temperature: float,
277
- top_p: float
278
- ) -> str:
279
- """Internal method to generate text (called in thread)."""
280
- # Tokenize input
281
- inputs = self.tokenizer(prompt, return_tensors="pt")
282
-
283
- # Move to same device as model if using CPU
284
- if next(self.model.parameters()).device.type == "cpu":
285
- inputs = {k: v.to("cpu") for k, v in inputs.items()}
286
- else:
287
- inputs = {k: v.to(next(self.model.parameters()).device) for k, v in inputs.items()}
288
-
289
- # Generate with optimized settings for better quality and speed
290
- with torch.no_grad():
291
- outputs = self.model.generate(
292
- **inputs,
293
- max_new_tokens=max_new_tokens,
294
- temperature=temperature,
295
- top_p=top_p,
296
- do_sample=True,
297
- eos_token_id=self.tokenizer.eos_token_id,
298
- pad_token_id=self.tokenizer.pad_token_id,
299
- use_cache=False, # Disabled: KV cache causes degradation after ~50 requests
300
- num_beams=1, # Greedy decoding is fastest (can adjust for quality)
301
- )
302
-
303
- # Decode - skip prompt tokens
304
- generated_text = self.tokenizer.decode(
305
- outputs[0][inputs["input_ids"].shape[1]:],
306
- skip_special_tokens=True
307
- )
308
-
309
- # Clear GPU cache to prevent memory accumulation and degradation
310
- if torch.cuda.is_available():
311
- torch.cuda.empty_cache()
312
-
313
- return generated_text.strip()
314
-
315
- def get_info(self) -> Dict[str, Any]:
316
- """Return model information for /models endpoint."""
317
- device = "unknown"
318
- dtype = "unknown"
319
- if self.model:
320
- device = str(next(self.model.parameters()).device)
321
- dtype = str(self.model.dtype)
322
-
323
- return {
324
- "name": self.name,
325
- "model_id": self.model_id,
326
- "type": "transformers",
327
- "backend": "huggingface-transformers",
328
- "loaded": self._initialized,
329
- "device": device,
330
- "dtype": dtype,
331
- "optimization": "float16, KV cache disabled (prevents degradation), 8-bit quantization",
332
- "note": "KV cache disabled to prevent quality degradation after 50+ requests"
333
- }
334
-
335
- async def cleanup(self) -> None:
336
- """Free memory."""
337
- import gc
338
-
339
- if self.model:
340
- del self.model
341
- self.model = None
342
- if self.tokenizer:
343
- del self.tokenizer
344
- self.tokenizer = None
345
- self._initialized = False
346
-
347
- # Aggressive cleanup
348
- gc.collect() # Force garbage collection
349
-
350
- # Clear CUDA cache if available
351
- if torch.cuda.is_available():
352
- torch.cuda.empty_cache()
353
- try:
354
- # Empty reserved memory too (PyTorch 2.0+)
355
- device_id = torch.cuda.current_device()
356
- torch.cuda.reset_peak_memory_stats(device_id)
357
- except:
358
- pass
359
-
360
- print(f"[{self.name}] Transformers Model unloaded and memory freed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/schemas/schemas.py DELETED
@@ -1,131 +0,0 @@
1
- from pydantic import BaseModel, Field
2
- from typing import List, Optional, Dict, Any
3
-
4
-
5
- class EnhancedDescriptionResponse(BaseModel):
6
- description: str
7
- model_used: str
8
- generation_time: float
9
- user_email: str
10
-
11
-
12
- # --- Batch Infill Schemas ---
13
-
14
- class InfillItem(BaseModel):
15
- """A single item (ad) with gaps to be filled."""
16
- id: str = Field(..., description="Unique identifier for this item")
17
- text_with_gaps: str = Field(..., description="Text containing [GAP:n] markers or ___ to fill")
18
- attributes: Dict[str, Any] = Field(default_factory=dict, description="Optional context attributes (e.g. make, model)")
19
- custom_messages: Optional[List[Dict[str, str]]] = Field(None, description="Optional pre-built chat messages to override prompt generation")
20
-
21
-
22
- class InfillOptions(BaseModel):
23
- """Configuration options for infill processing."""
24
- gap_notation: str = Field(
25
- default="auto",
26
- description="Gap notation: 'auto' (detect), '[GAP:n]', or '___'"
27
- )
28
- top_n_per_gap: int = Field(
29
- default=3,
30
- ge=1,
31
- le=5,
32
- description="Number of alternative suggestions per gap (1-5)"
33
- )
34
- language: str = Field(default="pl", description="Output language (pl/en)")
35
- temperature: float = Field(default=0.6, ge=0.0, le=1.0)
36
- max_new_tokens: int = Field(default=256, ge=50, le=512)
37
-
38
-
39
- class GapFill(BaseModel):
40
- """Result for a single filled gap."""
41
- index: int = Field(..., description="Gap index (1-based)")
42
- marker: str = Field(..., description="Original marker (e.g., '[GAP:1]' or '___')")
43
- choice: str = Field(..., description="Selected fill word/phrase")
44
- alternatives: List[str] = Field(
45
- default_factory=list,
46
- description="Alternative suggestions"
47
- )
48
-
49
-
50
- class InfillResult(BaseModel):
51
- """Result for a single infill item."""
52
- id: str
53
- status: str = Field(..., description="'ok' or 'error'")
54
- filled_text: Optional[str] = Field(None, description="Text with gaps filled")
55
- gaps: List[GapFill] = Field(default_factory=list)
56
- error: Optional[str] = Field(None, description="Error message if status='error'")
57
-
58
-
59
- class InfillRequest(BaseModel):
60
- """Request for single-model batch infill."""
61
- domain: str = Field(..., description="Domain name (e.g., 'cars')")
62
- items: List[InfillItem] = Field(..., description="Batch of items to process")
63
- model: str = Field(default="bielik-1.5b", description="Model to use")
64
- options: InfillOptions = Field(default_factory=InfillOptions)
65
-
66
-
67
- class InfillResponse(BaseModel):
68
- """Response for single-model batch infill."""
69
- model: str
70
- results: List[InfillResult]
71
- total_time: float
72
- processed_count: int
73
- error_count: int
74
-
75
-
76
- class CompareInfillRequest(BaseModel):
77
- """Request for multi-model batch infill comparison."""
78
- domain: str
79
- items: List[InfillItem]
80
- models: Optional[List[str]] = Field(
81
- None,
82
- description="Models to compare. If None, use all available."
83
- )
84
- options: InfillOptions = Field(default_factory=InfillOptions)
85
-
86
-
87
- class ModelInfillResult(BaseModel):
88
- """Per-model results in comparison."""
89
- model: str
90
- type: str
91
- results: List[InfillResult]
92
- time: float
93
- error_count: int
94
-
95
-
96
- class CompareInfillResponse(BaseModel):
97
- """Response for multi-model batch infill comparison."""
98
- domain: str
99
- models: List[ModelInfillResult]
100
- total_time: float
101
-
102
-
103
- class ModelInfo(BaseModel):
104
- name: str
105
- model_id: str
106
- type: str
107
- polish_support: str
108
- size: str
109
- loaded: bool
110
- active: Optional[bool] = None # Only for local models
111
-
112
-
113
- class CompareRequest(BaseModel):
114
- domain: str
115
- data: Dict[str, Any]
116
- models: Optional[List[str]] = None # If None, use all models
117
-
118
-
119
- class ModelResult(BaseModel):
120
- model: str
121
- output: str
122
- time: float
123
- type: str
124
- error: Optional[str] = None
125
-
126
-
127
- class CompareResponse(BaseModel):
128
- domain: str
129
- results: List[ModelResult]
130
- total_time: float
131
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,10 +0,0 @@
1
- fastapi==0.104.1
2
- uvicorn[standard]==0.24.0
3
- transformers==4.36.2
4
- accelerate==0.25.0
5
- bitsandbytes>=0.41.1
6
- huggingface_hub>=0.26.0
7
- pydantic==2.5.0
8
- importlib-metadata
9
- --extra-index-url https://download.pytorch.org/whl/cu121
10
- torch>=2.1.0
 
 
 
 
 
 
 
 
 
 
 
start_container.ps1 DELETED
@@ -1,23 +0,0 @@
1
- # PowerShell script to build and run the Docker container for your FastAPI service
2
-
3
- # Set variables
4
- $imageName = "bielik-fastapi-service"
5
- $containerName = "bielik_app_instance"
6
- $tokenFile = "my_hf_token.txt"
7
-
8
- Write-Host "Building Docker image..."
9
- docker build --secret id=huggingface_token,src=$tokenFile -t $imageName .
10
-
11
- Write-Host "Stopping and removing any existing container named $containerName..."
12
- docker stop $containerName | Out-Null 2>&1
13
-
14
- docker rm $containerName | Out-Null 2>&1
15
-
16
- Write-Host "Running new container..."
17
- docker run -d --name $containerName -p 8000:8000 $imageName
18
-
19
- Write-Host ""
20
- Write-Host "$containerName should be starting up."
21
- Write-Host "You can view logs with: docker logs $containerName -f"
22
- Write-Host "To stop the container, run: docker stop $containerName"
23
- Write-Host "The service will be available at http://127.0.0.1:8000"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
start_container.sh DELETED
@@ -1,25 +0,0 @@
1
- #!/bin/bash
2
-
3
- IMAGE_NAME="bielik-fastapi-service"
4
- CONTAINER_NAME="bielik_app_instance"
5
- TOKEN_FILE="my_hf_token.txt"
6
-
7
- # Build the Docker image with Hugging Face token as a secret
8
- echo "Building Docker image..."
9
- DOCKER_BUILDKIT=1 docker build --secret id=huggingface_token,src=$TOKEN_FILE -t $IMAGE_NAME .
10
-
11
- echo "Attempting to stop and remove existing container named $CONTAINER_NAME (if any)..."
12
- docker stop $CONTAINER_NAME > /dev/null 2>&1 || true # Stop if running, ignore error if not
13
- docker rm $CONTAINER_NAME > /dev/null 2>&1 || true # Remove if exists, ignore error if not
14
-
15
- echo "Starting new $IMAGE_NAME container as $CONTAINER_NAME..."
16
- docker run -d --name $CONTAINER_NAME -p 8000:8000 $IMAGE_NAME
17
- # -d : Runs the container in detached mode (in the background)
18
- # --name : Assigns a specific name to your running container instance
19
- # -p 8000:8000 : Maps port 8000 on your host to port 8000 in the container
20
-
21
- echo ""
22
- echo "$CONTAINER_NAME should be starting up."
23
- echo "You can view logs with: docker logs $CONTAINER_NAME -f"
24
- echo "To stop the container, run: docker stop $CONTAINER_NAME"
25
- echo "The service will be available at http://127.0.0.1:8000"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_simplified.py DELETED
@@ -1,132 +0,0 @@
1
- """
2
- Unit tests for simplified Bielik service
3
- Tests the API structure without running actual models
4
- """
5
- import os
6
- import json
7
- from unittest.mock import Mock, AsyncMock, patch
8
-
9
- # Skip llama-cpp installation during testing
10
- os.environ["SKIP_LLAMA_INSTALL"] = "1"
11
-
12
- # Mock the registry before importing main
13
- mock_registry = Mock()
14
- mock_registry.get_available_model_names.return_value = ["bielik-1.5b-transformer", "bielik-11b-transformer"]
15
- mock_registry.get_model_info.return_value = {"type": "transformers", "device": "cuda:0"}
16
-
17
- @patch("app.main.registry", mock_registry)
18
- def test_app_structure():
19
- """Test that simplified app has correct endpoints"""
20
- from app.main import app
21
-
22
- # Get all routes
23
- routes = {route.path: route.methods for route in app.routes}
24
-
25
- # Check required endpoints exist
26
- assert "/" in routes, "Root endpoint missing"
27
- assert "/health" in routes, "Health endpoint missing"
28
- assert "/models" in routes, "Models endpoint missing"
29
- assert "/chat" in routes, "Chat endpoint missing"
30
- assert "/generate" in routes, "Generate endpoint missing"
31
-
32
- # Check methods
33
- assert "GET" in routes["/health"], "Health should be GET"
34
- assert "GET" in routes["/models"], "Models should be GET"
35
- assert "POST" in routes["/chat"], "Chat should be POST"
36
- assert "POST" in routes["/generate"], "Generate should be POST"
37
-
38
- print("✅ App structure correct")
39
- print(f" Routes: {list(routes.keys())}")
40
-
41
- @patch("app.main.registry", mock_registry)
42
- def test_no_business_logic():
43
- """Verify no domain/infill endpoints exist"""
44
- from app.main import app
45
-
46
- routes = {route.path for route in app.routes}
47
-
48
- # These should NOT exist
49
- forbidden_routes = ["/enhance", "/compare", "/infill", "/compare-infill", "/user/me"]
50
-
51
- for route in forbidden_routes:
52
- assert route not in routes, f"Business logic endpoint {route} should not exist"
53
-
54
- print("✅ No business logic endpoints found")
55
-
56
- @patch("app.main.registry", mock_registry)
57
- def test_request_schemas():
58
- """Test request/response schemas are valid"""
59
- from app.main import ChatRequest, GenerateRequest, ChatResponse, GenerateResponse
60
- from app.main import Message, HealthResponse, ModelsResponse
61
-
62
- # Test ChatRequest
63
- chat_req = ChatRequest(
64
- model="bielik-1.5b-transformer",
65
- messages=[Message(role="user", content="Hello")]
66
- )
67
- assert chat_req.model == "bielik-1.5b-transformer"
68
- assert len(chat_req.messages) == 1
69
- print("✅ ChatRequest schema valid")
70
-
71
- # Test GenerateRequest
72
- gen_req = GenerateRequest(
73
- model="bielik-1.5b-transformer",
74
- prompt="Hello world"
75
- )
76
- assert gen_req.model == "bielik-1.5b-transformer"
77
- assert gen_req.prompt == "Hello world"
78
- print("✅ GenerateRequest schema valid")
79
-
80
- # Test HealthResponse
81
- health = HealthResponse(
82
- status="ok",
83
- gpu_available=True,
84
- models_available=2
85
- )
86
- assert health.status == "ok"
87
- print("✅ HealthResponse schema valid")
88
-
89
- # Test ModelsResponse
90
- models_resp = ModelsResponse(models=[])
91
- assert isinstance(models_resp.models, list)
92
- print("✅ ModelsResponse schema valid")
93
-
94
- @patch("app.main.registry", mock_registry)
95
- def test_default_values():
96
- """Test that requests have sensible defaults"""
97
- from app.main import ChatRequest, GenerateRequest, Message
98
-
99
- # Chat with minimal fields
100
- chat = ChatRequest(
101
- model="test",
102
- messages=[Message(role="user", content="test")]
103
- )
104
- assert chat.max_tokens == 150
105
- assert chat.temperature == 0.7
106
- assert chat.top_p == 0.9
107
- print("✅ Chat defaults correct")
108
-
109
- # Generate with minimal fields
110
- gen = GenerateRequest(
111
- model="test",
112
- prompt="test"
113
- )
114
- assert gen.max_tokens == 150
115
- assert gen.temperature == 0.7
116
- assert gen.top_p == 0.9
117
- print("✅ Generate defaults correct")
118
-
119
- if __name__ == "__main__":
120
- print("\n=== Testing Simplified Bielik Service ===\n")
121
-
122
- try:
123
- test_app_structure()
124
- test_no_business_logic()
125
- test_request_schemas()
126
- test_default_values()
127
-
128
- print("\n✅ All tests passed!")
129
- print("\n=== Phase 1 Verification Complete ===")
130
- except AssertionError as e:
131
- print(f"\n❌ Test failed: {e}")
132
- exit(1)