ganeshvb003 commited on
Commit
c51faba
·
verified ·
1 Parent(s): 3ca8149

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -0
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gradio
3
+ from huggingface_hub import hf_hub_download
4
+ from llama_cpp import Llama
5
+
6
+ # 1. Download the highly optimized Llama 3.2 3B model from Hugging Face repository
7
+ print("Downloading model... This happens only on the first run.")
8
+ model_path = hf_hub_download(
9
+ repo_id="bartowski/Llama-3.2-3B-Instruct-GGUF",
10
+ filename="Llama-3.2-3B-Instruct-Q4_K_M.gguf" # Compressed to fit perfectly in 16GB RAM
11
+ )
12
+
13
+ # 2. Initialize the model on the CPU
14
+ print("Initializing model...")
15
+ llm = Llama(
16
+ model_path=model_path,
17
+ n_ctx=2048, # Context length (how much text it remembers)
18
+ n_threads=2 # Utilizes both free CPU cores fully
19
+ )
20
+
21
+ # 3. Define the chatbot logic
22
+ def respond(message, chat_history):
23
+ # Format the prompt to match Llama 3.2 structural rules
24
+ formatted_prompt = "<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n"
25
+ formatted_prompt += "You are a helpful, direct, and honest AI assistant.<|eot_id|>"
26
+
27
+ # Inject chat history so the bot remembers the conversation context
28
+ for user_msg, bot_msg in chat_history:
29
+ if user_msg:
30
+ formatted_prompt += f"<|start_header_id|>user<|end_header_id|>\n{user_msg}<|eot_id|>"
31
+ if bot_msg:
32
+ formatted_prompt += f"<|start_header_id|>assistant<|end_header_id|>\n{bot_msg}<|eot_id|>"
33
+
34
+ # Add the newest user message
35
+ formatted_prompt += f"<|start_header_id|>user<|end_header_id|>\n{message}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n"
36
+
37
+ # Generate response tokens streamingly
38
+ output = llm(
39
+ formatted_prompt,
40
+ max_tokens=512,
41
+ stop=["<|eot_id|>"],
42
+ stream=True
43
+ )
44
+
45
+ token_accumulator = ""
46
+ for token in output:
47
+ token_text = token["choices"][0]["text"]
48
+ token_accumulator += token_text
49
+ yield token_accumulator
50
+
51
+ # 4. Create the web dashboard layout using Gradio
52
+ demo = gradio.ChatInterface(
53
+ fn=respond,
54
+ title="🤖 Free Llama 3.2 CPU Chatbot",
55
+ description="Running 24/7/365 for free on Hugging Face Spaces using CPU inference.",
56
+ examples=["Explain quantum computing simply.", "Write a short poem about coding."],
57
+ theme="soft"
58
+ )
59
+
60
+ if __name__ == "__main__":
61
+ demo.launch(server_name="0.0.0.0", server_port=7860)