Lachowski-V2 commited on
Commit
dfdd6ea
·
verified ·
1 Parent(s): 5c1d9ca

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -0
app.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from fastapi import FastAPI
3
+ from pydantic import BaseModel
4
+ from typing import List
5
+ import torch
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
7
+
8
+ app = FastAPI(title="Qwen 1.5B API")
9
+
10
+ model_id = "Qwen/Qwen2.5-1.5B-Instruct"
11
+
12
+ # Initialize model directly onto CPU
13
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
14
+ model = AutoModelForCausalLM.from_pretrained(
15
+ model_id,
16
+ torch_dtype=torch.float32,
17
+ device_map="cpu"
18
+ )
19
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
20
+
21
+ class Message(BaseModel):
22
+ role: str
23
+ content: str
24
+
25
+ class ChatPayload(BaseModel):
26
+ messages: List[Message]
27
+ temperature: float = 0.7
28
+ max_tokens: int = 512
29
+
30
+ @app.post("/v1/chat/completions")
31
+ async def chat_completion(payload: ChatPayload):
32
+ try:
33
+ # Convert incoming array to ChatML format
34
+ formatted_messages = [{"role": msg.role, "content": msg.content} for msg in payload.messages]
35
+
36
+ formatted_prompt = tokenizer.apply_chat_template(
37
+ formatted_messages,
38
+ tokenize=False,
39
+ add_generation_prompt=True
40
+ )
41
+
42
+ outputs = pipe(
43
+ formatted_prompt,
44
+ max_new_tokens=payload.max_tokens,
45
+ do_sample=True,
46
+ temperature=payload.temperature,
47
+ pad_token_id=tokenizer.eos_token_id
48
+ )
49
+
50
+ generated_text = outputs[0]["generated_text"]
51
+ response_content = generated_text[len(formatted_prompt):].strip()
52
+
53
+ # Mirror the clean OpenAI JSON standard response
54
+ return {
55
+ "choices": [
56
+ {
57
+ "message": {
58
+ "role": "assistant",
59
+ "content": response_content
60
+ }
61
+ }
62
+ ]
63
+ }
64
+ except Exception as e:
65
+ return {"error": str(e)}
66
+
67
+ @app.get("/")
68
+ async def health():
69
+ return {"status": "online"}
70
+
71
+ if __name__ == "__main__":
72
+ import uvicorn
73
+ uvicorn.run(app, host="0.0.0.0", port=7860)