Tom716 commited on
Commit
3d4900d
·
verified ·
1 Parent(s): 0515363

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import threading
3
+ import time
4
+ import subprocess
5
+ import gradio as gr
6
+ from ollama import Client
7
+
8
+ # 1. Start Ollama Server in a background thread
9
+ # We don't need to install it anymore; Docker did that!
10
+ def ollama_service_thread():
11
+ # We use 'serve' to start the background process
12
+ subprocess.run("ollama serve", shell=True)
13
+
14
+ threading.Thread(target=ollama_service_thread, daemon=True).start()
15
+
16
+ # 2. Wait for the server to wake up
17
+ print("Waiting for Ollama to start...")
18
+ time.sleep(10) # Give it a moment
19
+
20
+ # 3. Download the model (runs only if not already present)
21
+ # Llama 3.2 3B is small and fast!
22
+ MODEL = "llama3.2:3b"
23
+ print(f"Checking/Pulling model: {MODEL}...")
24
+ subprocess.run(f"ollama pull {MODEL}", shell=True)
25
+
26
+ # 4. Connect the Client
27
+ client = Client(host='http://127.0.0.1:11434')
28
+
29
+ # 5. The Chat Logic
30
+ def chat(message, history, temperature, max_new_tokens, top_p, top_k, penalty):
31
+ # Format history for the model
32
+ conversation = []
33
+ for prompt, answer in history:
34
+ conversation.extend([
35
+ {"role": "user", "content": prompt},
36
+ {"role": "assistant", "content": answer},
37
+ ])
38
+ conversation.append({"role": "user", "content": message})
39
+
40
+ # Call the API
41
+ response = client.chat(
42
+ model=MODEL,
43
+ messages=conversation,
44
+ stream=True,
45
+ options={
46
+ "num_predict": max_new_tokens,
47
+ "temperature": temperature,
48
+ "top_p": top_p,
49
+ "top_k": top_k,
50
+ "repeat_penalty": penalty,
51
+ }
52
+ )
53
+
54
+ # Stream the output
55
+ partial_message = ""
56
+ for chunk in response:
57
+ if 'message' in chunk and 'content' in chunk['message']:
58
+ content = chunk['message']['content']
59
+ partial_message += content
60
+ yield partial_message
61
+
62
+ # 6. The UI
63
+ with gr.Blocks() as demo:
64
+ gr.HTML("<h1>🦙 Llama 3.2 3B on HF Docker</h1>")
65
+
66
+ gr.ChatInterface(
67
+ fn=chat,
68
+ additional_inputs=[
69
+ gr.Slider(0, 1, 0.7, label="Temperature"),
70
+ gr.Slider(128, 4096, 1024, label="Max New Tokens"),
71
+ gr.Slider(0.0, 1.0, 0.9, label="Top P"),
72
+ gr.Slider(1, 100, 40, label="Top K"),
73
+ gr.Slider(0.0, 2.0, 1.1, label="Repetition Penalty"),
74
+ ]
75
+ )
76
+
77
+ if __name__ == "__main__":
78
+ demo.launch(server_name="0.0.0.0", server_port=7860)