Spaces:
Sleeping

File size: 10,539 Bytes
a02eb7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import subprocess
import os
import logging
from flask import Flask, request, jsonify
from flask_cors import CORS

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Detect if running in Docker/container environment
IS_DOCKER = os.path.exists("/llama.cpp") or os.environ.get("DOCKER_CONTAINER", "").lower() == "true"

if IS_DOCKER:
    # Docker/container paths
    MODEL_PATH = "model/lfm2-q5_km.gguf"
    LLAMA_BIN = "/llama.cpp/build/bin/llama-cli"
else:
    # Local development paths
    MODEL_PATH = os.path.join(os.path.dirname(__file__), "model", "lfm2-q5_km.gguf")
    LLAMA_BIN = os.path.join(os.path.dirname(__file__), "llama.cpp", "build", "bin", "llama-cli")
    # For Windows compatibility
    if os.name == 'nt':
        LLAMA_BIN += ".exe"
        # Windows Release build puts binaries in Release subdirectory
        release_path = LLAMA_BIN.replace("bin\\llama-cli.exe", "bin\\Release\\llama-cli.exe")
        if os.path.exists(release_path):
            LLAMA_BIN = release_path

SYSTEM_PROMPT = "<|startoftext|><|im_start|>system\nYou are a helpful assistant trained by Liquid AI.<|im_end|>\n"

app = Flask(__name__)
CORS(app)  # Enable CORS for cross-origin requests

def validate_paths():
    """Validate that required files exist"""
    errors = []
    if not os.path.exists(MODEL_PATH):
        errors.append(f"Model not found at: {MODEL_PATH}")
    if not os.path.exists(LLAMA_BIN):
        errors.append(f"llama-cli not found at: {LLAMA_BIN}")
    return errors

def generate_text(user_prompt, ctx_size=4096, threads=2, temp=0.3, min_p=0.15, 

                 repeat_penalty=1.05, max_tokens=512):
    """

    Generate text using llama.cpp

    

    Args:

        user_prompt: The user's input prompt

        ctx_size: Context window size

        threads: Number of threads to use

        temp: Temperature for sampling

        min_p: Minimum probability threshold

        repeat_penalty: Repetition penalty

        max_tokens: Maximum number of tokens to generate

    

    Returns:

        Generated text response

    """
    # Format prompt according to LFM2 ChatML format
    prompt = (
        SYSTEM_PROMPT
        + f"<|im_start|>user\n{user_prompt}<|im_end|>\n"
        + "<|im_start|>assistant\n"
    )

    cmd = [
        LLAMA_BIN,
        "-m", MODEL_PATH,
        "--ctx-size", str(ctx_size),
        "--threads", str(threads),
        "--temp", str(temp),
        "--min-p", str(min_p),
        "--repeat-penalty", str(repeat_penalty),
        "-n", str(max_tokens),
        "-p", prompt,
        "--no-display-prompt",  # Don't echo the prompt
        "--simple-io",  # Use simple IO for cleaner output
        "-no-cnv"  # Disable conversation mode for cleaner output
    ]

    try:
        logger.info(f"Running inference with prompt length: {len(prompt)}")
        logger.info(f"Command: {' '.join(cmd[:5])}...")  # Log first part of command
        
        # Use Popen for better control and to handle stderr separately
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding='utf-8',
            errors='ignore',
            bufsize=1  # Line buffered
        )
        
        try:
            stdout, stderr = process.communicate(timeout=300)  # 5 minute timeout
        except subprocess.TimeoutExpired:
            process.kill()
            stdout, stderr = process.communicate()
            logger.error(f"Inference timed out. stderr: {stderr[:200] if stderr else 'None'}")
            raise Exception("Inference timed out after 5 minutes")
        
        if process.returncode != 0:
            error_msg = stderr or stdout or "Unknown error"
            logger.error(f"llama.cpp exited with code {process.returncode}")
            logger.error(f"Error output: {error_msg[:500]}")
            raise Exception(f"Inference failed: {error_msg[:500]}")
        
        # Log stderr for debugging (contains model loading info)
        if stderr:
            logger.debug(f"llama.cpp stderr (first 200 chars): {stderr[:200]}")
        
        # Extract the generated text from output
        output = stdout.strip() if stdout else ""
        
        # The output may contain the prompt echoed back, metadata, and the response
        # Look for the assistant tag and extract everything after it
        assistant_marker = "<|im_start|>assistant\n"
        if assistant_marker in output:
            # Extract everything after the assistant marker
            response = output.split(assistant_marker, 1)[-1]
        elif prompt in output:
            # Fallback: if prompt is in output, get everything after it
            response = output.split(prompt, 1)[-1]
        else:
            # If neither marker found, use the whole output (might be just the response)
            response = output
        
        # Clean up: remove any trailing metadata or performance info
        # Look for common patterns that indicate end of generation
        lines = response.split('\n')
        cleaned_lines = []
        for line in lines:
            # Stop at performance info or metadata markers
            if any(marker in line.lower() for marker in [
                'common_perf_print',
                'llama_memory_breakdown',
                'sampler seed:',
                'sampler params:',
                'generate:',
                'system_info:',
                'load:',
                'llama_model_loader:',
                'print_info:'
            ]):
                break
            cleaned_lines.append(line)
        
        response = '\n'.join(cleaned_lines).strip()
        
        # Remove any remaining prompt fragments
        if prompt[:50] in response:  # Check first 50 chars to avoid full prompt match issues
            response = response.replace(prompt[:50], "").strip()
        
        # Remove common end markers
        response = response.replace("[end of text]", "").strip()
        response = response.replace("<|endoftext|>", "").strip()
        response = response.replace("<|im_end|>", "").strip()
        
        if not response:
            logger.warning("Empty response from llama.cpp")
            # If output is empty, check stderr for clues
            if stderr:
                logger.warning(f"stderr content: {stderr[:300]}")
            response = "No response generated"
        
        logger.info(f"Generated response length: {len(response)}")
        return response
    except subprocess.TimeoutExpired:
        logger.error("Inference timed out")
        raise Exception("Inference timed out after 5 minutes")
    except Exception as e:
        error_msg = str(e)
        logger.error(f"Error during inference: {error_msg}")
        # Don't re-raise if it's already our custom exception
        if "timed out" in error_msg or "Inference failed" in error_msg:
            raise
        raise Exception(f"Unexpected error during inference: {error_msg}")

@app.route("/generate", methods=["POST"])
def generate():
    """Generate text from user prompt"""
    try:
        data = request.get_json(force=True)
        if not data:
            return jsonify({"error": "No JSON data provided"}), 400
        
        user_prompt = data.get("prompt", "")
        if not user_prompt:
            return jsonify({"error": "Prompt is required"}), 400
        
        # Optional parameters with defaults (conservative for free tier)
        ctx_size = int(data.get("ctx_size", 4096))
        threads = int(data.get("threads", 2))
        temp = float(data.get("temp", 0.3))
        min_p = float(data.get("min_p", 0.15))
        repeat_penalty = float(data.get("repeat_penalty", 1.05))
        max_tokens = int(data.get("max_tokens", 512))
        
        # Enforce limits for free tier safety
        ctx_size = min(ctx_size, 4096)
        threads = min(threads, 4)
        max_tokens = min(max_tokens, 512)
        
        response = generate_text(
            user_prompt,
            ctx_size=ctx_size,
            threads=threads,
            temp=temp,
            min_p=min_p,
            repeat_penalty=repeat_penalty,
            max_tokens=max_tokens
        )
        
        return jsonify({"response": response})
    
    except ValueError as e:
        return jsonify({"error": f"Invalid parameter: {str(e)}"}), 400
    except Exception as e:
        logger.error(f"Error in /generate: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route("/health", methods=["GET"])
def health():
    """Health check endpoint"""
    errors = validate_paths()
    if errors:
        return jsonify({
            "status": "error",
            "errors": errors
        }), 503
    
    return jsonify({
        "status": "ok",
        "model_path": MODEL_PATH,
        "llama_bin": LLAMA_BIN,
        "environment": "docker" if IS_DOCKER else "local"
    })

@app.route("/", methods=["GET"])
def root():
    """Root endpoint with API information"""
    return jsonify({
        "service": "LFM2 GGUF Backend",
        "version": "1.0.0",
        "status": "✅ LFM2 GGUF server is running",
        "endpoints": {
            "POST /generate": "Generate text from a prompt",
            "GET /health": "Check service health"
        },
        "example_request": {
            "url": "/generate",
            "method": "POST",
            "body": {
                "prompt": "What is C. elegans?",
                "temp": 0.3,
                "max_tokens": 512
            }
        }
    })

if __name__ == "__main__":
    # Validate paths on startup
    errors = validate_paths()
    if errors:
        logger.warning("Startup validation errors:")
        for error in errors:
            logger.warning(f"  - {error}")
        logger.warning("Service will start but may not function correctly.")
    
    port = int(os.environ.get("PORT", 7860))
    host = os.environ.get("HOST", "0.0.0.0")
    
    logger.info(f"Starting Flask server on {host}:{port}")
    logger.info(f"Environment: {'Docker' if IS_DOCKER else 'Local'}")
    logger.info(f"Model path: {MODEL_PATH}")
    logger.info(f"llama-cli path: {LLAMA_BIN}")
    
    app.run(host=host, port=port, debug=False)