Spaces:
Runtime error
Runtime error
File size: 5,724 Bytes
557cccb 509395e 0253dda a20f569 0321702 a20f569 9699d19 557cccb e1ec073 557cccb a20f569 557cccb a20f569 5bb1b16 a20f569 5bb1b16 a20f569 9699d19 5bb1b16 f112ebb 5bb1b16 a20f569 da5a23d 9699d19 7e30ffe 9699d19 f4e8f75 2984668 a20f569 9699d19 cc7609b 9699d19 330a031 9699d19 330a031 9699d19 557cccb 9699d19 6677c43 bb73263 9699d19 bb73263 6391002 9699d19 a20f569 557cccb 2984668 e1ec073 9699d19 2984668 9699d19 2984668 9699d19 2984668 e1ec073 2984668 557cccb 9699d19 557cccb 509395e 2984668 e1ec073 9699d19 2984668 9699d19 2984668 9699d19 2984668 e1ec073 2984668 509395e 9699d19 509395e 875bdae 21d088c 5556a56 509395e 9699d19 557cccb a20f569 9699d19 a20f569 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | import os
import time
from flask import Flask, request, render_template, jsonify, Response
from flasgger import Swagger, swag_from
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
from huggingface_hub import login
from langchain_community.tools import DuckDuckGoSearchRun
# β
Safe import of GPU decorator
try:
from spaces import GPU
except ImportError:
def GPU(func): return func
# Flask + Swagger setup
app = Flask(__name__, static_folder="static", template_folder="templates")
swagger = Swagger(app, template={
"swagger": "2.0",
"info": {
"title": "ChatMate Real-Time API",
"description": "LangChain + DuckDuckGo enabled AI chatbot",
"version": "1.0"
}
}, config={
"headers": [],
"specs": [{"endpoint": 'apispec', "route": '/apispec.json', "rule_filter": lambda rule: True}],
"static_url_path": "/flasgger_static",
"swagger_ui": True,
"specs_route": "/apidocs/"
})
# β
Hugging Face login (if token provided)
login(token=os.environ.get("CHAT_MATE"))
# β
Load LLaMA 3.1 Instruct model
model_id = "meta-llama/Llama-3.1-8B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", device_map="auto")
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=512)
# β
Simple keyword-based check for real-time info
REAL_TIME_KEYWORDS = {"latest", "current", "news", "today", "price", "time", "live", "trending", "update", "happening"}
def should_search(message):
message = message.lower()
return any(kw in message for kw in REAL_TIME_KEYWORDS)
# β
Search tool
search_tool = DuckDuckGoSearchRun()
# β
Chat using model with chat template and history
@GPU
def generate_full_reply(message, history):
system_prompt = "You are a helpful and concise AI assistant."
messages = [{"role": "system", "content": system_prompt}] + history + [{"role": "user", "content": message}]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
output = pipe(prompt, do_sample=True, temperature=0.7)[0]["generated_text"]
return output.split(prompt)[-1].strip()
# β
Flask route
@app.route("/")
def home():
return render_template("index.html")
@app.route("/chat", methods=["POST"])
@swag_from({
'tags': ['Chat'],
'consumes': ['application/json'],
'summary': 'Get assistant reply',
'description': 'Send a message and chat history, and receive a full AI-generated response.',
'parameters': [{
'name': 'body',
'in': 'body',
'required': True,
'schema': {
'type': 'object',
'properties': {
'message': {'type': 'string', 'example': 'What is Python?'},
'history': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'role': {'type': 'string', 'example': 'user'},
'content': {'type': 'string', 'example': 'Tell me about Python'}
}
}
}
},
'required': ['message']
}
}],
'responses': {
200: {
'description': 'Assistant reply',
'schema': {
'type': 'object',
'properties': {
'reply': {'type': 'string'}
}
}
}
}
})
def chat():
data = request.get_json()
message = data.get("message")
history = data.get("history", [])
# Check if real-time search is needed
if should_search(message):
result = f"(Live info) {search_tool.run(message)}"
else:
result = generate_full_reply(message, history)
return jsonify({"reply": result})
@app.route("/chat-stream", methods=["POST"])
@swag_from({
'tags': ['Chat'],
'consumes': ['application/json'],
'summary': 'Stream assistant reply',
'description': 'Send a message and history, receive AI-generated text as a stream (token by token).',
'parameters': [{
'name': 'body',
'in': 'body',
'required': True,
'schema': {
'type': 'object',
'properties': {
'message': {'type': 'string', 'example': 'Explain quantum computing.'},
'history': {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'role': {'type': 'string', 'example': 'user'},
'content': {'type': 'string', 'example': 'What is entanglement?'}
}
}
}
},
'required': ['message']
}
}],
'responses': {
200: {
'description': 'Streamed reply',
'content': {'text/plain': {}}
}
}
})
def chat_stream():
data = request.get_json()
message = data.get("message")
history = data.get("history", [])
def generate():
# if should_search(message):
# reply = f"(Live info) {search_tool.run(message)}"
# else:
reply = generate_full_reply(message, history)
for token in reply.splitlines(keepends=True):
yield token
time.sleep(0.05)
return Response(generate(), mimetype='text/plain')
# β
Warm-up on startup
if __name__ == "__main__":
print("π§ Warming up...")
_ = generate_full_reply("Hello", [])
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
|