Tom716 commited on
Commit
8faca8d
·
verified ·
1 Parent(s): c5c8b77

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -93
app.py CHANGED
@@ -2,108 +2,49 @@ 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 (Standard Setup)
9
- def ollama_service_thread():
10
- subprocess.run("ollama serve", shell=True)
11
 
12
- threading.Thread(target=ollama_service_thread, daemon=True).start()
13
 
14
- # Wait for server to wake up
15
- print("Waiting for Ollama to start...")
16
  time.sleep(10)
17
-
18
- # 2. Pull the Model
19
  MODEL = "llama3.2:3b"
20
  subprocess.run(f"ollama pull {MODEL}", shell=True)
 
21
 
22
- # 3. Connect Client
23
- client = Client(host='http://127.0.0.1:11434')
24
-
25
- # --- FUNCTION A: FOR THE WEB UI (Streaming) ---
26
- # This uses 'yield' to type out words one by one.
27
- def chat_ui(message, history, temperature, max_new_tokens, top_p, top_k, penalty):
28
- conversation = []
29
- for prompt, answer in history:
30
- conversation.extend([
31
- {"role": "user", "content": prompt},
32
- {"role": "assistant", "content": answer},
33
- ])
34
- conversation.append({"role": "user", "content": message})
35
-
36
- response = client.chat(
37
- model=MODEL,
38
- messages=conversation,
39
- stream=True,
40
- options={
41
- "num_predict": max_new_tokens,
42
- "temperature": temperature,
43
- "top_p": top_p,
44
- "top_k": top_k,
45
- "repeat_penalty": penalty,
46
- }
47
- )
48
-
49
- partial_message = ""
50
- for chunk in response:
51
- if 'message' in chunk and 'content' in chunk['message']:
52
- partial_message += chunk['message']['content']
53
- yield partial_message
54
 
55
- # --- FUNCTION B: FOR n8n (Blocking / No Stream) ---
56
- # This uses 'return' to send the full text at once.
57
- # This prevents the 404/Timeout errors in n8n.
58
- def chat_n8n(message, temperature, max_new_tokens, top_p, top_k, penalty):
59
- conversation = [{"role": "user", "content": message}]
60
 
61
- response = client.chat(
62
- model=MODEL,
63
- messages=conversation,
64
- stream=False, # <--- CRITICAL: No streaming for API
65
- options={
66
- "num_predict": max_new_tokens,
67
- "temperature": temperature,
68
- "top_p": top_p,
69
- "top_k": top_k,
70
- "repeat_penalty": penalty,
71
- }
72
  )
73
- return response['message']['content']
74
 
75
- # --- THE INTERFACE ---
76
- with gr.Blocks() as demo:
77
- gr.HTML("<h1>🦙 Llama 3.2 (Dual Mode: UI + API)</h1>")
78
-
79
- # 1. The Visible Chatbot (Uses Streaming Function A)
80
- gr.ChatInterface(
81
- fn=chat_ui,
82
- additional_inputs=[
83
- gr.Slider(0, 1, 0.7, label="Temperature"),
84
- gr.Slider(128, 4096, 1024, label="Max Tokens"),
85
- gr.Slider(0.0, 1.0, 0.9, label="Top P"),
86
- gr.Slider(1, 100, 40, label="Top K"),
87
- gr.Slider(0.0, 2.0, 1.1, label="Penalty"),
88
- ]
89
- )
90
-
91
- # 2. The Hidden API Route (Uses Blocking Function B)
92
- # We create a button that is invisible but defines the API name "n8n"
93
- api_btn = gr.Button("API Call", visible=False)
94
- api_btn.click(
95
- fn=chat_n8n,
96
- inputs=[
97
- gr.Textbox(), # Message
98
- gr.Number(value=0.7), # Temp
99
- gr.Number(value=1024), # Tokens
100
- gr.Number(value=0.9), # Top P
101
- gr.Number(value=40), # Top K
102
- gr.Number(value=1.1) # Penalty
103
- ],
104
- outputs=gr.Textbox(),
105
- api_name="n8n" # <--- THIS IS THE KEY. It creates /api/n8n
106
- )
107
 
108
- if __name__ == "__main__":
109
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
2
  import threading
3
  import time
4
  import subprocess
5
+ from flask import Flask, request, Response, stream_with_context
6
+ import requests
7
 
8
+ # 1. Start Ollama Server
9
+ def run_ollama():
10
+ subprocess.Popen(["ollama", "serve"])
11
 
12
+ threading.Thread(target=run_ollama, daemon=True).start()
13
 
14
+ # 2. Wait & Pull Model
15
+ print("Waiting for Ollama...")
16
  time.sleep(10)
 
 
17
  MODEL = "llama3.2:3b"
18
  subprocess.run(f"ollama pull {MODEL}", shell=True)
19
+ print("Model Ready!")
20
 
21
+ # 3. Create a Proxy App (Flask)
22
+ app = Flask(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ # This forwards everything from /v1/* to local Ollama
25
+ @app.route('/v1/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
26
+ def proxy(path):
27
+ url = f"http://127.0.0.1:11434/v1/{path}"
 
28
 
29
+ # Forward the request to Ollama
30
+ resp = requests.request(
31
+ method=request.method,
32
+ url=url,
33
+ headers={key: value for (key, value) in request.headers if key != 'Host'},
34
+ data=request.get_data(),
35
+ cookies=request.cookies,
36
+ allow_redirects=False,
37
+ stream=True
 
 
38
  )
 
39
 
40
+ # Stream the response back to n8n
41
+ def generate():
42
+ for chunk in resp.iter_content(chunk_size=4096):
43
+ if chunk:
44
+ yield chunk
45
+
46
+ return Response(generate(), status=resp.status_code, headers=dict(resp.headers))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ if __name__ == '__main__':
49
+ # Run on port 7860 (Hugging Face default)
50
+ app.run(host='0.0.0.0', port=7860)