oleh13 commited on
Commit
dc560db
·
verified ·
1 Parent(s): 2e2af1b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from typing import List, Optional
4
+ from huggingface_hub import hf_hub_download
5
+ from llama_cpp import Llama
6
+ import uvicorn
7
+
8
+ app = FastAPI(title="ChemLLM CPU OpenAI API")
9
+
10
+ print("Завантаження GGUF моделі...")
11
+ model_path = hf_hub_download(
12
+ repo_id="RichardErkhov/AI4Chem___ChemLLM-7B-Chat-1_5-DPO-gguf",
13
+ filename="ChemLLM-7B-Chat-1_5-DPO.Q4_K_M.gguf"
14
+ )
15
+
16
+ llm = Llama(model_path=model_path, n_ctx=2048, n_threads=4)
17
+ print("Модель успішно завантажена на CPU!")
18
+
19
+ class ChatMessage(BaseModel):
20
+ role: str
21
+ content: str
22
+
23
+ class ChatCompletionRequest(BaseModel):
24
+ model: str
25
+ messages: List[ChatMessage]
26
+ temperature: Optional[float] = 0.7
27
+ max_tokens: Optional[int] = 256
28
+
29
+ @app.post("/v1/chat/completions")
30
+ async def chat_completions(request: ChatCompletionRequest):
31
+ try:
32
+ full_prompt = ""
33
+ for msg in request.messages:
34
+ if msg.role == "user":
35
+ full_prompt += f"<|User|>:{msg.content}"
36
+ elif msg.role == "assistant":
37
+ full_prompt += f"<|Bot|>:{msg.content}"
38
+ full_prompt += "<|Bot|>:"
39
+
40
+ # Виклик генерації на CPU
41
+ output = llm(
42
+ full_prompt,
43
+ max_tokens=request.max_tokens,
44
+ temperature=request.temperature,
45
+ stop=["<|User|>", "<|Bot|>", "\n\n"]
46
+ )
47
+
48
+ response_text = output["choices"][0]["text"].strip()
49
+
50
+ return {
51
+ "id": "chatcmpl-chem-cpu",
52
+ "object": "chat.completion",
53
+ "model": request.model,
54
+ "choices": [{
55
+ "index": 0,
56
+ "message": {
57
+ "role": "assistant",
58
+ "content": response_text
59
+ },
60
+ "finish_reason": "stop"
61
+ }]
62
+ }
63
+ except Exception as e:
64
+ raise HTTPException(status_code=500, detail=str(e))
65
+
66
+ @app.get("/")
67
+ def health():
68
+ return {"status": "healthy", "hardware": "CPU"}
69
+
70
+ if __name__ == "__main__":
71
+ uvicorn.run(app, host="0.0.0.0", port=7860)