Hướng dẫnAI Translated Content

Self-Hosted LLMs cho Doanh Nghiệp #4

Đội ngũ Float16
2 min read
Self-Hosted LLMs cho Doanh Nghiệp #4

Đây là phần cuối cùng để triển khai mô hình LLM của riêng bạn. Sau khi thiết lập tất cả các dịch vụ và công cụ cần thiết trong các phần trước, hãy tiếp tục với việc tải xuống mô hình và tạo API Endpoint.

Đối với những người mới đọc phần này là phần đầu tiên, bạn có thể làm theo các phần trước tại:

Phần 1

Phần 2

Phần 3

Hãy bắt đầu Phần 4!!

1. Tạo Dự án và Tải xuống Mô hình

# 1. Tạo thư mục cho dự án
mkdir -p llm-chat-api
cd llm-chat-api
# 2. Tải xuống mô hình (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

Tệp mô hình sẽ được lưu trữ tại ./model/Llama-3.2-1B-Instruct-Q8_0.gguf

2. Tạo Tệp Python để Chạy Mô hình

Tạo tệp 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"])

Kiểm tra chạy với:

python3 main.py

3. Mở API với FastAPI

Cài đặt FastAPI và Uvicorn (server)

pip install fastapi uvicorn pydantic

Cập nhật main.py để là REST API với 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. Chạy API Server

uvicorn main:app --host 0.0.0.0 --port 8000

API sẽ có sẵn tại http://localhost:8000/chat

Chúng ta có thể kiểm tra nó qua curl:

curl -X POST http://localhost:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Describe a sunset over the ocean."}'

Tóm Tắt Tổng Thể

Từ tất cả các phần, chúng ta có thể tạo một endpoint LLM đơn giản để đội sử dụng, dù để thử nghiệm hay phát triển thành các sản phẩm khác nhau. Cuối cùng, tôi muốn yêu cầu mọi người tiếp tục theo dõi các bài viết khác. Tôi đảm bảo sẽ có nội dung thú vị để theo dõi.