Trigger82 commited on
Commit
dbee570
Β·
verified Β·
1 Parent(s): e650bc4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -60
app.py CHANGED
@@ -1,64 +1,114 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ import torch
5
+ import os
6
+ import logging
7
+
8
+ # Configure logging
9
+ logging.basicConfig(level=logging.INFO)
10
+ logger = logging.getLogger(__name__)
11
+
12
+ # Hugging Face Spaces path setup
13
+ HF_SPACE = os.getenv("SPACE_ID", "")
14
+ BASE_PATH = f"/spaces/{HF_SPACE}" if HF_SPACE else ""
15
+
16
+ # FastAPI initialization
17
+ app = FastAPI(
18
+ title="Phi-2 Chat API",
19
+ description="Chatbot API using microsoft/phi-2, CPU-optimized",
20
+ version="1.0",
21
+ root_path=BASE_PATH,
22
+ docs_url="/docs" if not BASE_PATH else f"{BASE_PATH}/docs",
23
+ redoc_url=None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  )
25
 
26
+ # Load model and tokenizer
27
+ try:
28
+ logger.info("Loading Phi-2 tokenizer and model...")
29
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2")
30
+ model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2")
31
+ logger.info("Model loaded successfully!")
32
+ except Exception as e:
33
+ logger.error(f"Model loading failed: {str(e)}")
34
+ raise RuntimeError("Model initialization failed") from e
35
+
36
+ # In-memory chat history
37
+ chat_history = {}
38
+
39
+ # System prompt to guide tone
40
+ SYSTEM_PROMPT = (
41
+ "You are a helpful, chill, clever, and fun AI assistant called 𝕴 𝖆𝖒 π–π–Žπ–’. "
42
+ "Talk like a smooth, witty friend. Be friendly and humanlike.\n"
43
+ )
44
+
45
+ @app.get("/", include_in_schema=False)
46
+ async def root():
47
+ return {"message": "🟒 Phi-2 API is live. Use /ai?query=Hello&user_id=yourname"}
48
+
49
+ @app.get("/ai")
50
+ async def chat(request: Request):
51
+ try:
52
+ user_input = request.query_params.get("query", "").strip()
53
+ user_id = request.query_params.get("user_id", "default").strip()
54
+
55
+ if not user_input:
56
+ raise HTTPException(status_code=400, detail="Missing 'query' parameter.")
57
+ if len(user_input) > 200:
58
+ raise HTTPException(status_code=400, detail="Query too long (max 200 characters)")
59
+
60
+ # Retrieve last conversation
61
+ user_history = chat_history.get(user_id, [])
62
+ history_prompt = ""
63
+
64
+ for entry in user_history[-3:]: # Last 3 exchanges
65
+ history_prompt += f"User: {entry['q']}\nAI: {entry['a']}\n"
66
+ full_prompt = SYSTEM_PROMPT + history_prompt + f"User: {user_input}\nAI:"
67
+
68
+ # Tokenize and generate
69
+ input_ids = tokenizer(full_prompt, return_tensors="pt").input_ids
70
+ output_ids = model.generate(
71
+ input_ids,
72
+ max_new_tokens=100,
73
+ temperature=0.8,
74
+ top_p=0.95,
75
+ do_sample=True,
76
+ pad_token_id=tokenizer.eos_token_id
77
+ )
78
+
79
+ response = tokenizer.decode(output_ids[0][input_ids.shape[-1]:], skip_special_tokens=True).strip()
80
+
81
+ # Store updated history
82
+ user_history.append({"q": user_input, "a": response})
83
+ chat_history[user_id] = user_history
84
+
85
+ return {"reply": response}
86
+
87
+ except Exception as e:
88
+ logger.error(f"Error: {e}")
89
+ raise HTTPException(status_code=500, detail=f"Processing error: {str(e)}") from e
90
+
91
+ @app.get("/health")
92
+ async def health_check():
93
+ return {
94
+ "status": "healthy",
95
+ "model": "microsoft/phi-2",
96
+ "users": len(chat_history),
97
+ "space_id": HF_SPACE
98
+ }
99
+
100
+ @app.get("/reset")
101
+ async def reset_history(user_id: str = "default"):
102
+ if user_id in chat_history:
103
+ del chat_history[user_id]
104
+ return {"status": "success", "message": f"History cleared for user {user_id}"}
105
 
106
  if __name__ == "__main__":
107
+ import uvicorn
108
+ uvicorn.run(
109
+ app,
110
+ host="0.0.0.0",
111
+ port=7860,
112
+ log_level="info",
113
+ timeout_keep_alive=30
114
+ )