Spaces:
Running
Running
Delete llm.py
Browse files
llm.py
DELETED
@@ -1,149 +0,0 @@
|
|
1 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
2 |
-
from langchain_core.prompts import PromptTemplate
|
3 |
-
import os
|
4 |
-
from typing import List
|
5 |
-
|
6 |
-
class LLM:
|
7 |
-
def __init__(self, model_repo: str = "Qwen/Qwen2-1.5B-Instruct",
|
8 |
-
local_path: str = "models"):
|
9 |
-
"""
|
10 |
-
Initialize the LLM with Qwen2-1.5B-Instruct using Hugging Face Transformers.
|
11 |
-
|
12 |
-
Args:
|
13 |
-
model_repo (str): Hugging Face repository ID for the model.
|
14 |
-
local_path (str): Local directory to store the model.
|
15 |
-
"""
|
16 |
-
os.makedirs(local_path, exist_ok=True)
|
17 |
-
|
18 |
-
try:
|
19 |
-
# Load the model
|
20 |
-
self.llm = AutoModelForCausalLM.from_pretrained(
|
21 |
-
model_repo,
|
22 |
-
device_map="auto", # Automatically map to CPU
|
23 |
-
cache_dir=local_path,
|
24 |
-
trust_remote_code=True
|
25 |
-
)
|
26 |
-
|
27 |
-
# Load the tokenizer
|
28 |
-
self.tokenizer = AutoTokenizer.from_pretrained(
|
29 |
-
model_repo,
|
30 |
-
cache_dir=local_path,
|
31 |
-
trust_remote_code=True
|
32 |
-
)
|
33 |
-
print(f"Model successfully loaded from {model_repo}")
|
34 |
-
except Exception as e:
|
35 |
-
raise RuntimeError(
|
36 |
-
f"Failed to initialize model from {model_repo}. "
|
37 |
-
f"Please ensure the model is available at https://huggingface.co/{model_repo}. "
|
38 |
-
f"Error: {str(e)}"
|
39 |
-
)
|
40 |
-
|
41 |
-
# Define prompt template for query parsing (used in query_parser.py)
|
42 |
-
self.prompt_template = PromptTemplate(
|
43 |
-
template="""Bạn là một trợ lý phân tích truy vấn nhà hàng. Phân tích truy vấn sau và trích xuất các đặc trưng: cuisine, menu, price_range, distance, rating, và description. Chỉ trích xuất các giá trị khớp chính xác với danh sách giá trị hợp lệ. Nếu không tìm thấy giá trị khớp, trả về null (hoặc [] cho menu). Loại bỏ các từ khóa đã trích xuất khỏi description. Trả về kết quả dưới dạng JSON.
|
44 |
-
|
45 |
-
**Danh sách giá trị hợp lệ**:
|
46 |
-
- cuisine: {cuisines}
|
47 |
-
- menu: {dishes}
|
48 |
-
- price_range: {price_ranges}
|
49 |
-
|
50 |
-
**Hướng dẫn**:
|
51 |
-
- cuisine: Chỉ chọn giá trị từ danh sách cuisine. Ví dụ, "Viet" → "Vietnamese".
|
52 |
-
- menu: Chỉ chọn các món khớp chính xác với danh sách menu. Ví dụ, "phở bò" → "phở", "sushi" → [].
|
53 |
-
- price_range: Chỉ chọn {price_ranges}. Ví dụ, "cheap" → "low".
|
54 |
-
- distance: Trích xuất số km (e.g., "2 km" → 2.0) hoặc từ khóa ["nearby", "close" → 2.0, "far" → 10.0]. Nếu không rõ, trả về null.
|
55 |
-
- rating: Trích xuất số (e.g., "4 stars" → 4.0). Nếu không rõ, trả về null.
|
56 |
-
- description: Phần còn lại sau khi loại bỏ các từ khóa đã trích xuất. Nếu rỗng, trả về truy vấn gốc.
|
57 |
-
|
58 |
-
**Truy vấn**: {query}
|
59 |
-
|
60 |
-
**Định dạng đầu ra**:
|
61 |
-
{{
|
62 |
-
"cuisine": null | "tên loại ẩm thực",
|
63 |
-
"menu": [],
|
64 |
-
"price_range": null | "low" | "medium" | "high",
|
65 |
-
"distance": null | số km | "nearby" | "close" | "far",
|
66 |
-
"rating": null | số,
|
67 |
-
"description": "phần mô tả còn lại"
|
68 |
-
}}
|
69 |
-
""",
|
70 |
-
input_variables=["cuisines", "dishes", "price_ranges", "query"]
|
71 |
-
)
|
72 |
-
|
73 |
-
def generate(self, prompt: str, max_length: int = 1000) -> str:
|
74 |
-
"""
|
75 |
-
Generate text using the LLM.
|
76 |
-
|
77 |
-
Args:
|
78 |
-
prompt (str): Input prompt.
|
79 |
-
max_length (int): Maximum length of the generated text.
|
80 |
-
|
81 |
-
Returns:
|
82 |
-
str: Generated text.
|
83 |
-
"""
|
84 |
-
try:
|
85 |
-
# Apply chat template for instruction-tuned Qwen model
|
86 |
-
messages = [{"role": "user", "content": prompt}]
|
87 |
-
prompt_with_template = self.tokenizer.apply_chat_template(
|
88 |
-
messages, tokenize=False, add_generation_prompt=True
|
89 |
-
)
|
90 |
-
# Tokenize input prompt
|
91 |
-
inputs = self.tokenizer(prompt_with_template, return_tensors="pt").to(self.llm.device)
|
92 |
-
# Generate text
|
93 |
-
outputs = self.llm.generate(
|
94 |
-
**inputs,
|
95 |
-
max_new_tokens=max_length,
|
96 |
-
temperature=0.7,
|
97 |
-
do_sample=True,
|
98 |
-
pad_token_id=self.tokenizer.eos_token_id
|
99 |
-
)
|
100 |
-
# Decode the generated tokens
|
101 |
-
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
102 |
-
print("Response generated successfully!")
|
103 |
-
return response.strip()
|
104 |
-
except Exception as e:
|
105 |
-
raise RuntimeError(f"Failed to generate response: {str(e)}")
|
106 |
-
|
107 |
-
def format_query_prompt(self, query: str, cuisines: List[str], dishes: List[str], price_ranges: List[str]) -> str:
|
108 |
-
"""
|
109 |
-
Format the prompt for query parsing using the prompt template.
|
110 |
-
|
111 |
-
Args:
|
112 |
-
query (str): User query.
|
113 |
-
cuisines (list): List of valid cuisines.
|
114 |
-
dishes (list): List of valid dishes.
|
115 |
-
price_ranges (list): List of valid price ranges.
|
116 |
-
|
117 |
-
Returns:
|
118 |
-
str: Formatted prompt.
|
119 |
-
"""
|
120 |
-
return self.prompt_template.format(
|
121 |
-
cuisines=cuisines,
|
122 |
-
dishes=dishes,
|
123 |
-
price_ranges=price_ranges,
|
124 |
-
query=query
|
125 |
-
)
|
126 |
-
|
127 |
-
if __name__ == "__main__":
|
128 |
-
# Khởi tạo đối tượng LLM với model_repo và local_path
|
129 |
-
local_path = 'models'
|
130 |
-
|
131 |
-
try:
|
132 |
-
# Khởi tạo đối tượng LLM
|
133 |
-
llm = LLM(local_path=local_path)
|
134 |
-
|
135 |
-
# Định nghĩa một truy vấn và các tham số cần thiết
|
136 |
-
query = "Tìm quán ăn Việt Nam gần đây, giá rẻ với món phở và cơm tấm"
|
137 |
-
cuisines = ["Vietnamese", "Chinese", "Italian"]
|
138 |
-
dishes = ["phở", "sushi", "pasta", "cơm tấm"]
|
139 |
-
price_ranges = ["low", "medium", "high"]
|
140 |
-
|
141 |
-
# Sử dụng hàm generate để tạo câu trả lời từ truy vấn
|
142 |
-
generated_text = llm.generate(query, max_length=300)
|
143 |
-
|
144 |
-
# In kết quả ra màn hình
|
145 |
-
print("Generated text:")
|
146 |
-
print(generated_text)
|
147 |
-
|
148 |
-
except Exception as e:
|
149 |
-
print(f"Error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|