File size: 2,080 Bytes
69b2834 | 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 | from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from llama_cpp import Llama
from typing import List, Dict
app = FastAPI(title="Gemma 4 API Server")
# Инициализация модели со строгим лимитом на 2 потока CPU (для стабильности бесплатного тарифа)
print("Загрузка модели Gemma 4...")
llm = Llama(
model_path="/code/model.gguf",
n_ctx=2048,
n_threads=2
)
print("Модель успешно загружена!")
class Message(BaseModel):
role: str
content: str
class ChatCompletionRequest(BaseModel):
model: str = "local"
messages: List[Dict[str, str]]
temperature: float = 0.7
max_tokens: int = 500
@app.post("/v1/chat/completions")
async def chat_completions(request: ChatCompletionRequest):
try:
# Формируем промпт из истории сообщений
prompt = ""
for msg in request.messages:
role = msg.get("role", "user")
content = msg.get("content", "")
prompt += f"<|im_start|>{role}\n{content}<|im_end|>\n"
prompt += "<|im_start|>assistant\n"
# Генерация ответа
output = llm(
prompt,
max_tokens=request.max_tokens,
temperature=request.temperature,
stop=["<|im_end|>", "<|im_start|>"]
)
text_response = output["choices"][0]["text"].strip()
# Формируем ответ, идентичный OpenAI API структуре
return {
"choices": [
{
"message": {
"role": "assistant",
"content": text_response
},
"finish_reason": "stop",
"index": 0
}
]
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/")
def read_root():
return {"status": "Gemma 4 API is running"}
|