Nhughes09 commited on
Commit Β·
77ed406
1
Parent(s): 2c396c2
DeepSeek chatbot with Ollama + setup instructions for visitors
Browse files- app.py +121 -49
- requirements.txt +1 -1
app.py
CHANGED
|
@@ -1,45 +1,88 @@
|
|
| 1 |
-
# app.py -
|
| 2 |
import gradio as gr
|
|
|
|
| 3 |
import logging
|
| 4 |
import sys
|
| 5 |
import traceback
|
| 6 |
from datetime import datetime
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
logging.basicConfig(
|
| 11 |
-
level=logging.INFO,
|
| 12 |
-
format="%(asctime)s | %(levelname)-8s | %(message)s",
|
| 13 |
-
handlers=[logging.StreamHandler(sys.stdout)]
|
| 14 |
-
)
|
| 15 |
logger = logging.getLogger("CHATBOT")
|
| 16 |
|
| 17 |
logger.info("=" * 60)
|
| 18 |
-
logger.info("
|
| 19 |
logger.info("=" * 60)
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
| 24 |
|
| 25 |
-
|
|
|
|
| 26 |
try:
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
# Chat function
|
| 45 |
request_count = 0
|
|
@@ -51,12 +94,11 @@ def chat_with_ai(message, history):
|
|
| 51 |
|
| 52 |
logger.info(f"[{rid}] User: {message}")
|
| 53 |
|
| 54 |
-
if
|
| 55 |
-
return "
|
| 56 |
|
| 57 |
try:
|
| 58 |
-
|
| 59 |
-
prompt = "You are a helpful AI assistant.\n\n"
|
| 60 |
if history:
|
| 61 |
for item in history:
|
| 62 |
if isinstance(item, dict):
|
|
@@ -73,30 +115,60 @@ def chat_with_ai(message, history):
|
|
| 73 |
|
| 74 |
prompt += f"User: {message}\nAssistant:"
|
| 75 |
|
| 76 |
-
logger.info(f"[{rid}]
|
| 77 |
start = datetime.now()
|
| 78 |
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
elapsed = (datetime.now() - start).total_seconds()
|
| 82 |
-
response = output["choices"][0]["text"].strip()
|
| 83 |
-
|
| 84 |
-
logger.info(f"[{rid}] Response in {elapsed:.1f}s: {response[:100]}...")
|
| 85 |
-
return response
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
except Exception as e:
|
| 88 |
logger.error(f"[{rid}] Error: {e}")
|
| 89 |
-
logger.error(traceback.format_exc())
|
| 90 |
return f"Error: {e}"
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
logger.info("Building
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
logger.info("READY!")
|
| 102 |
|
|
|
|
| 1 |
+
# app.py - Local Ollama Chatbot with DeepSeek
|
| 2 |
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
import logging
|
| 5 |
import sys
|
| 6 |
import traceback
|
| 7 |
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
# Logging
|
| 10 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(message)s", handlers=[logging.StreamHandler(sys.stdout)])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
logger = logging.getLogger("CHATBOT")
|
| 12 |
|
| 13 |
logger.info("=" * 60)
|
| 14 |
+
logger.info(" DEEPSEEK CHATBOT - LOCAL OLLAMA")
|
| 15 |
logger.info("=" * 60)
|
| 16 |
|
| 17 |
+
# Config
|
| 18 |
+
OLLAMA_URL = "http://localhost:11434"
|
| 19 |
+
MODEL = "deepseek-coder:6.7b-instruct-q6_K"
|
| 20 |
|
| 21 |
+
# Check connection
|
| 22 |
+
ollama_connected = False
|
| 23 |
try:
|
| 24 |
+
resp = requests.get(f"{OLLAMA_URL}/api/tags", timeout=3)
|
| 25 |
+
if resp.status_code == 200:
|
| 26 |
+
models = [m["name"] for m in resp.json().get("models", [])]
|
| 27 |
+
if MODEL in models:
|
| 28 |
+
ollama_connected = True
|
| 29 |
+
logger.info(f"Ollama connected! Using {MODEL}")
|
| 30 |
+
else:
|
| 31 |
+
logger.warning(f"Model {MODEL} not found. Available: {models}")
|
| 32 |
+
except:
|
| 33 |
+
logger.warning("Ollama not running")
|
| 34 |
+
|
| 35 |
+
# Install instructions
|
| 36 |
+
INSTALL_INSTRUCTIONS = """
|
| 37 |
+
# π Local AI Chatbot Setup
|
| 38 |
+
|
| 39 |
+
This chatbot runs on **YOUR computer** using Ollama + DeepSeek AI.
|
| 40 |
+
|
| 41 |
+
## Step 1: Install Ollama
|
| 42 |
+
|
| 43 |
+
**Mac:**
|
| 44 |
+
```bash
|
| 45 |
+
brew install ollama
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
**Linux:**
|
| 49 |
+
```bash
|
| 50 |
+
curl -fsSL https://ollama.com/install.sh | sh
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
**Windows:** Download from [ollama.com/download](https://ollama.com/download)
|
| 54 |
+
|
| 55 |
+
---
|
| 56 |
+
|
| 57 |
+
## Step 2: Start Ollama & Download Model
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
# Start Ollama (run in terminal, keep open)
|
| 61 |
+
ollama serve
|
| 62 |
+
|
| 63 |
+
# Download DeepSeek model (6.7GB, one-time)
|
| 64 |
+
ollama pull deepseek-coder:6.7b-instruct-q6_K
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
---
|
| 68 |
+
|
| 69 |
+
## Step 3: Refresh This Page
|
| 70 |
+
|
| 71 |
+
Once Ollama is running with the model, **refresh this page** and the chat will work!
|
| 72 |
+
|
| 73 |
+
---
|
| 74 |
+
|
| 75 |
+
### Alternative: Clone & Run Locally
|
| 76 |
+
|
| 77 |
+
```bash
|
| 78 |
+
git clone https://huggingface.co/spaces/ndwdgda/cpu
|
| 79 |
+
cd cpu
|
| 80 |
+
pip install gradio requests
|
| 81 |
+
python app.py
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Then open http://127.0.0.1:7860
|
| 85 |
+
"""
|
| 86 |
|
| 87 |
# Chat function
|
| 88 |
request_count = 0
|
|
|
|
| 94 |
|
| 95 |
logger.info(f"[{rid}] User: {message}")
|
| 96 |
|
| 97 |
+
if not ollama_connected:
|
| 98 |
+
return "β Ollama not connected! See the Setup tab for instructions."
|
| 99 |
|
| 100 |
try:
|
| 101 |
+
prompt = "You are a helpful AI coding assistant.\n\n"
|
|
|
|
| 102 |
if history:
|
| 103 |
for item in history:
|
| 104 |
if isinstance(item, dict):
|
|
|
|
| 115 |
|
| 116 |
prompt += f"User: {message}\nAssistant:"
|
| 117 |
|
| 118 |
+
logger.info(f"[{rid}] Calling DeepSeek...")
|
| 119 |
start = datetime.now()
|
| 120 |
|
| 121 |
+
resp = requests.post(
|
| 122 |
+
f"{OLLAMA_URL}/api/generate",
|
| 123 |
+
json={"model": MODEL, "prompt": prompt, "stream": False},
|
| 124 |
+
timeout=120
|
| 125 |
+
)
|
| 126 |
|
| 127 |
elapsed = (datetime.now() - start).total_seconds()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
if resp.status_code == 200:
|
| 130 |
+
result = resp.json()
|
| 131 |
+
text = result.get("response", "")
|
| 132 |
+
logger.info(f"[{rid}] Response in {elapsed:.1f}s: {text[:100]}...")
|
| 133 |
+
return text.strip()
|
| 134 |
+
else:
|
| 135 |
+
return f"Error: {resp.status_code} - {resp.text[:200]}"
|
| 136 |
+
|
| 137 |
except Exception as e:
|
| 138 |
logger.error(f"[{rid}] Error: {e}")
|
|
|
|
| 139 |
return f"Error: {e}"
|
| 140 |
|
| 141 |
+
# UI
|
| 142 |
+
logger.info("Building UI...")
|
| 143 |
+
|
| 144 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 145 |
+
gr.Markdown("# π€ DeepSeek AI Chatbot")
|
| 146 |
+
|
| 147 |
+
if ollama_connected:
|
| 148 |
+
gr.Markdown(f"**β
Connected to Ollama** | Model: `{MODEL}`")
|
| 149 |
+
else:
|
| 150 |
+
gr.Markdown("**β Ollama not connected** - See **Setup** tab below for instructions!")
|
| 151 |
+
|
| 152 |
+
with gr.Tabs():
|
| 153 |
+
with gr.TabItem("π¬ Chat"):
|
| 154 |
+
chatbot = gr.Chatbot(height=400)
|
| 155 |
+
msg = gr.Textbox(placeholder="Ask me anything..." if ollama_connected else "Install Ollama first (see Setup tab)", label="Message")
|
| 156 |
+
with gr.Row():
|
| 157 |
+
send = gr.Button("Send", variant="primary")
|
| 158 |
+
clear = gr.ClearButton([msg, chatbot])
|
| 159 |
+
|
| 160 |
+
def respond(message, history):
|
| 161 |
+
if not message.strip():
|
| 162 |
+
return "", history
|
| 163 |
+
bot_response = chat_with_ai(message, history)
|
| 164 |
+
history = history + [[message, bot_response]]
|
| 165 |
+
return "", history
|
| 166 |
+
|
| 167 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 168 |
+
send.click(respond, [msg, chatbot], [msg, chatbot])
|
| 169 |
+
|
| 170 |
+
with gr.TabItem("π Setup"):
|
| 171 |
+
gr.Markdown(INSTALL_INSTRUCTIONS)
|
| 172 |
|
| 173 |
logger.info("READY!")
|
| 174 |
|
requirements.txt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
gradio==4.19.2
|
| 2 |
huggingface_hub==0.22.2
|
| 3 |
-
|
|
|
|
| 1 |
gradio==4.19.2
|
| 2 |
huggingface_hub==0.22.2
|
| 3 |
+
requests
|