File size: 2,978 Bytes
4625807
ec97b47
4625807
 
 
d6ff847
4625807
 
 
76f1775
 
 
 
 
 
4625807
 
76f1775
 
4625807
 
76f1775
4625807
 
 
 
 
7e2c46b
4625807
 
 
 
 
 
76f1775
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4625807
76f1775
 
 
 
 
 
 
 
 
 
4625807
76f1775
4625807
 
 
 
 
 
 
 
 
 
76f1775
 
 
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
# vllm_backend.py
import time, logging
from typing import Any, Dict, AsyncIterable

from vllm.sampling_params import SamplingParams
from backends_base import ChatBackend, ImagesBackend

logger = logging.getLogger(__name__)

try:
    import spaces
except ImportError:
    spaces = None


class VLLMChatBackend(ChatBackend):
    """
    On ZeroGPU: build vLLM engine per request (no persistent state).
    Returns a single ChatCompletionChunk with the full text.
    """

    async def stream(self, request: Dict[str, Any]) -> AsyncIterable[Dict[str, Any]]:
        messages = request.get("messages", [])
        prompt = messages[-1]["content"] if messages else "(empty)"

        params = SamplingParams(
            temperature=float(request.get("temperature", 0.7)),
            max_tokens=int(request.get("max_tokens", 512))
        )

        rid = f"chatcmpl-local-{int(time.time())}"
        now = int(time.time())
        model_name = request.get("model", "local-vllm")

        # GPU wrapper for ZeroGPU
        if spaces:
            @spaces.GPU(duration=60)
            def run_once(prompt: str) -> str:
                from vllm.engine.async_llm_engine import AsyncLLMEngine
                from vllm.engine.arg_utils import AsyncEngineArgs

                args = AsyncEngineArgs(model=model_name, trust_remote_code=True)
                engine = AsyncLLMEngine.from_engine_args(args)

                # synchronous generate
                outputs = list(engine.generate(prompt, params, request_id=rid))
                return outputs[-1].outputs[0].text if outputs else ""

        else:
            def run_once(prompt: str) -> str:
                from vllm.engine.async_llm_engine import AsyncLLMEngine
                from vllm.engine.arg_utils import AsyncEngineArgs

                args = AsyncEngineArgs(model=model_name, trust_remote_code=True)
                engine = AsyncLLMEngine.from_engine_args(args)

                outputs = list(engine.generate(prompt, params, request_id=rid))
                return outputs[-1].outputs[0].text if outputs else ""

        try:
            text = run_once(prompt)
            yield {
                "id": rid,
                "object": "chat.completion.chunk",
                "created": now,
                "model": model_name,
                "choices": [
                    {"index": 0, "delta": {"content": text}, "finish_reason": "stop"}
                ],
            }
        except Exception:
            logger.exception("vLLM inference failed")
            raise


class StubImagesBackend(ImagesBackend):
    """
    vLLM does not support image generation.
    For now, return a transparent PNG placeholder.
    """
    async def generate_b64(self, request: Dict[str, Any]) -> str:
        logger.warning("Image generation not supported in local vLLM backend.")
        return (
            "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP4BwQACfsD/etCJH0AAAAASUVORK5CYII="
        )