Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,106 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
app = FastAPI()
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
@app.get("/")
|
| 7 |
def greet_json():
|
| 8 |
-
return {"Hello": "World!"}
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from vllm import AsyncLLMEngine, SamplingParams
|
| 5 |
+
from vllm.engine.arg_utils import AsyncEngineArgs
|
| 6 |
+
import json
|
| 7 |
+
import uuid
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
+
engine = AsyncLLMEngine.from_engine_args(
|
| 12 |
+
AsyncEngineArgs(
|
| 13 |
+
model='microsoft/Phi-3-mini-4k-instruct',
|
| 14 |
+
max_num_batched_tokens=4096, # Adjust based on GPU memory
|
| 15 |
+
max_num_seqs=32, # Limit concurrent sequences
|
| 16 |
+
gpu_memory_utilization=0.85, # Target 85% GPU memory utilization
|
| 17 |
+
max_model_len=4096, # Match the model's context length
|
| 18 |
+
enforce_eager=False, # Enable CUDA graph optimization
|
| 19 |
+
dtype='half', # Use half-precision for reduced memory usage
|
| 20 |
+
)
|
| 21 |
+
)
|
| 22 |
|
| 23 |
+
class GenerationRequest(BaseModel):
|
| 24 |
+
# FastAPI uses classes like GenerationRequest for several important reasons:
|
| 25 |
+
# - Automatic Request Parsing
|
| 26 |
+
# - Data Validation
|
| 27 |
+
# - Default Values
|
| 28 |
+
# - Self-Documenting APIs
|
| 29 |
+
# - Type Safety in Your Code
|
| 30 |
+
prompt: str
|
| 31 |
+
max_tokens: int = 100
|
| 32 |
+
temperature: float = 0.7
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
async def generate_stream(prompt: str, max_tokens: int, temperature: float):
|
| 36 |
+
"""
|
| 37 |
+
The function generate_stream is an asynchronous generator that produces a stream of
|
| 38 |
+
text from a language model. Asynchronous functions can pause their execution,
|
| 39 |
+
allowing other code to run while waiting for operations to complete.
|
| 40 |
+
|
| 41 |
+
prompt: The initial text to start the generation.
|
| 42 |
+
max_tokens: The maximum number of tokens (words or word pieces) to generate.
|
| 43 |
+
temperature: Controls the randomness of the generation. Higher values (e.g., 1.0)
|
| 44 |
+
make output more random, while lower values (e.g., 0.1) make it more deterministic.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
# SamplingParams configures how the text generation will behave.
|
| 48 |
+
# It uses the temperature and max_tokens values passed to the function.
|
| 49 |
+
sampling_params = SamplingParams(
|
| 50 |
+
temperature=temperature,
|
| 51 |
+
max_tokens=max_tokens
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# The request_id is used by vLLM to track different generation requests,
|
| 55 |
+
# especially useful in scenarios with multiple concurrent requests.
|
| 56 |
+
# Using a UUID ensures that each request has a unique identifier,
|
| 57 |
+
# preventing conflicts between different generation tasks.
|
| 58 |
+
request_id = str(uuid.uuid4())
|
| 59 |
+
|
| 60 |
+
# async for is an asynchronous loop that works with asynchronous generators.
|
| 61 |
+
# engine.generate() is an instance of the language model that generates text
|
| 62 |
+
# based on the given prompt and parameters. The loop will receive chunks of
|
| 63 |
+
# generated text one at a time rather than waiting for the entire text to be generated.
|
| 64 |
+
# The generate function requires a request_id, which I set to 1
|
| 65 |
+
async for output in engine.generate(prompt, sampling_params, request_id=request_id):
|
| 66 |
+
# yield is used in generator functions to produce a series of values
|
| 67 |
+
# over time rather than computing them all at once. The yielded string
|
| 68 |
+
# follows the Server-Sent Events (SSE) format:
|
| 69 |
+
# - It starts with "data: ".
|
| 70 |
+
# - The content is a JSON string containing the generated text.
|
| 71 |
+
# - It ends with two newlines (\n\n) to signal the end of an SSE message.
|
| 72 |
+
yield f"data: {json.dumps({'text': output.outputs[0].text})}\n\n"
|
| 73 |
+
|
| 74 |
+
# After the generation is complete, we yield a special "DONE" signal,
|
| 75 |
+
# also in SSE format, to indicate that the stream has ended.
|
| 76 |
+
yield "data: [DONE]\n\n"
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# This line tells FastAPI that this function should handle POST requests
|
| 80 |
+
# to the "/generate-stream" endpoint.
|
| 81 |
+
@app.post("/generate-stream")
|
| 82 |
+
async def generate_text(request: GenerationRequest):
|
| 83 |
+
"""
|
| 84 |
+
The function generate_text is a FastAPI route that handles POST requests to "/generate-stream".
|
| 85 |
+
It's designed to stream generated text back to the client as it's being produced
|
| 86 |
+
rather than waiting for all the text to be generated before sending a response.
|
| 87 |
+
"""
|
| 88 |
+
try:
|
| 89 |
+
# StreamingResponse is used to send a streaming response back to the client.
|
| 90 |
+
# generate_stream() is called with the parameters from the request. This function is expected to be a generator that yields chunks of text.
|
| 91 |
+
# media_type="text/event-stream" indicates that this is a Server-Sent Events (SSE) stream, a format for sending real-time updates from server to client.
|
| 92 |
+
return StreamingResponse(
|
| 93 |
+
generate_stream(request.prompt, request.max_tokens, request.temperature),
|
| 94 |
+
media_type="text/event-stream"
|
| 95 |
+
)
|
| 96 |
+
except Exception as e:
|
| 97 |
+
# If an exception occurs, it returns a streaming response with an error message,
|
| 98 |
+
# maintaining the SSE format.
|
| 99 |
+
return StreamingResponse(
|
| 100 |
+
iter([f"data: {json.dumps({'error': str(e)})}\n\n"]),
|
| 101 |
+
media_type="text/event-stream"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
@app.get("/")
|
| 105 |
def greet_json():
|
| 106 |
+
return {"Hello": "World!"}
|