Self-Hosted LLMs for Enterprise #4

ตอนสุดท้ายแล้วนะครับ สำหรับการ deploy llm model ใช้งานเอง หลังจากที่แล้ว Setup ตัว service และ tools ต่างๆที่ต้องการครบถ้วนแล้ว เรามาลุยกันต่อเลยครับในการ download model และทำ API Endpoint
สำหรับใครที่เพิ่งเข้ามาอ่านตอนนี้เป็นตอนแรก สามารถติดตามตอนก่อนหน้าได้ที่
https://blog.float16.cloud/self-hosted-llms-for-enterprise-/
https://blog.float16.cloud/self-hosted-llms-for-enterprise-2/
https://blog.float16.cloud/self-hosted-llms-for-enterprise-3/
ไปเริ่มตอนที่ 4 กันเลย !!
1.สร้างโปรเจกต์และดาวน์โหลดโมเดล
# 1. สร้างโฟลเดอร์สำหรับโปรเจกต์
mkdir -p llm-chat-api
cd llm-chat-api
# 2. ดาวน์โหลดโมเดล (Llama 3.2 1B Q8_0)
huggingface-cli download bartowski/Llama-3.2-1B-Instruct-GGUF \
Llama-3.2-1B-Instruct-Q8_0.gguf --local-dir model
ไฟล์โมเดลจะถูกเก็บไว้ใน ./model/Llama-3.2-1B-Instruct-Q8_0.gguf
2.สร้าง Python ไฟล์เพื่อรันโมเดล
สร้างไฟล์ main.py
# main.py
from llama_cpp import Llama
llm = Llama(
model_path="model/Llama-3.2-1B-Instruct-Q8_0.gguf",
n_gpu_layers=-1,
verbose=False,
chat_format='llama-3'
)
output = llm.create_chat_completion(
messages=[
{"role": "system", "content": "You are an best assistant"},
{"role": "user", "content": "Introduce yourself"}
]
)
print(output["choices"][0]["message"]["content"])
ทดสอบรันด้วย
python3 main.py
3.เปิด API ด้วย FastAPI
ติดตั้ง FastAPI และ Uvicorn (server)
pip install fastapi uvicorn pydantic
อัปเดต main.py ให้เป็น REST API แบบ POST
# main.py
from fastapi import FastAPI
from pydantic import BaseModel
from llama_cpp import Llama
app = FastAPI()
llm = Llama(
model_path="model/Llama-3.2-1B-Instruct-Q8_0.gguf",
n_gpu_layers=-1,
verbose=False,
chat_format='llama-3'
)
class PromptRequest(BaseModel):
prompt: str
@app.post("/chat")
def chat(req: PromptRequest):
response = llm.create_chat_completion(
messages=[
{"role": "system", "content": "You are an assistant who can help to answer general question"},
{"role": "user", "content": req.prompt}
]
)
return {"response": response["choices"][0]["message"]["content"]}
4.รัน API Server
uvicorn main:app --host 0.0.0.0 --port 8000
API จะเปิดให้ใช้งานที่ http://localhost:8000/chat
โดยเราสามารถทดลองเรียกใช้งานได้ผ่าน curl
curl -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"prompt": "Describe a sunset over the ocean."}'
บทสรุปของทั้งหมด
จากทุกตอนที่ผ่านเรา เราจะสามารถทำ llm endpoint เอาไว้ใช้งานง่ายๆในทีม ไม่ว่าจะเอามาใช้ทดสอบ หรือนำไปพัฒนาเป็น product ต่างๆต่อไป สุดท้ายนี้อยากฝากทุกคนให้ติดตามบทความอื่นต่อไปด้วยนะครับ รับรองว่ามีอะไรที่น่าสนใจมาให้ติดตามต่อแน่นอนครับ