Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.prompts import PromptTemplate
|
| 2 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 3 |
+
from langchain_community.llms import CTransformers
|
| 4 |
+
import os
|
| 5 |
+
# Cài thư việt trước
|
| 6 |
+
# ! pip install langchain langchain-community ctransformers
|
| 7 |
+
|
| 8 |
+
MODEL_FILE = "Cube-Python.gguf"
|
| 9 |
+
MODEL_TYPE = "llama"
|
| 10 |
+
GPU_LAYERS = 0 # Nếu máy có GPU VRAM nhiều hơn có thể chỉnh lên 10-20 để trả lời nhanh hơn
|
| 11 |
+
CONTEXT_LENGTH = 4096
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_llm_with_ctransformers():
|
| 15 |
+
model_path = os.path.join(os.getcwd(), MODEL_FILE)
|
| 16 |
+
|
| 17 |
+
if not os.path.exists(model_path):
|
| 18 |
+
raise FileNotFoundError(f"File mô hình {MODEL_FILE} không tồn tại.")
|
| 19 |
+
|
| 20 |
+
llm = CTransformers(
|
| 21 |
+
model=model_path,
|
| 22 |
+
model_type=MODEL_TYPE,
|
| 23 |
+
config={
|
| 24 |
+
'max_new_tokens': 1024,
|
| 25 |
+
'temperature': 0.1,
|
| 26 |
+
'gpu_layers': GPU_LAYERS,
|
| 27 |
+
'context_length': CONTEXT_LENGTH,
|
| 28 |
+
}
|
| 29 |
+
)
|
| 30 |
+
return llm
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
template = """[INST] Bạn là một trợ lý AI chuyên nghiệp về lập trình Python.
|
| 34 |
+
Hãy viết code Python chất lượng cao để giải quyết yêu cầu sau.
|
| 35 |
+
Ưu tiên:
|
| 36 |
+
- code rõ ràng
|
| 37 |
+
- có thể chạy được
|
| 38 |
+
- đặt tên biến dễ hiểu
|
| 39 |
+
Chỉ trả lời bằng code.
|
| 40 |
+
Yêu cầu: {question} [/INST]"""
|
| 41 |
+
|
| 42 |
+
prompt = PromptTemplate(
|
| 43 |
+
input_variables=["question"],
|
| 44 |
+
template=template
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
llm = load_llm_with_ctransformers()
|
| 48 |
+
|
| 49 |
+
parser = StrOutputParser()
|
| 50 |
+
|
| 51 |
+
chain = prompt | llm | parser
|
| 52 |
+
|
| 53 |
+
question = '''
|
| 54 |
+
Write a Python program that takes a sentence as input and removes all punctuation marks
|
| 55 |
+
from it.
|
| 56 |
+
Input:
|
| 57 |
+
A sentence: "Hello! This is a NLP practical exam, isn't it?"
|
| 58 |
+
Desired Output:
|
| 59 |
+
Hello This is a NLP practical exam isnt it'''
|
| 60 |
+
|
| 61 |
+
result = chain.invoke({"question": question})
|
| 62 |
+
|
| 63 |
+
print(result)
|