PraneshJs commited on
Commit
904d7f0
·
verified ·
1 Parent(s): 4264352

added app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import redis
4
+ from openai import AzureOpenAI
5
+
6
+ # Redis Cloud connection
7
+ redis_client = redis.Redis(
8
+ host='redis-12628.c14.us-east-1-2.ec2.redns.redis-cloud.com',
9
+ port=12628,
10
+ decode_responses=True,
11
+ username="default",
12
+ password=os.getenv("REDIS_PASSWORD") # store password as HF secret
13
+ )
14
+
15
+ # Azure OpenAI client
16
+ client = AzureOpenAI(
17
+ api_key=os.getenv("AZURE_OPENAI_API_KEY").strip(),
18
+ api_version="2024-05-01-preview",
19
+ azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT").strip()
20
+ )
21
+ DEPLOYMENT_NAME = " gpt-4.1"
22
+
23
+ def chat_with_ai(user_input):
24
+ if not user_input:
25
+ return "Please type something."
26
+
27
+ # Check Redis first
28
+ cached = redis_client.get(user_input)
29
+ if cached:
30
+ return f"[From Redis] {cached}"
31
+
32
+ # Otherwise query Azure OpenAI
33
+ response = client.chat.completions.create(
34
+ model=DEPLOYMENT_NAME,
35
+ messages=[{"role": "user", "content": user_input}],
36
+ max_tokens=150
37
+ )
38
+ output = response.choices[0].message.content.strip()
39
+
40
+ # Save in Redis
41
+ redis_client.setex(user_input, 3600, output)
42
+
43
+ return f"[From OpenAI] {output}"
44
+
45
+ # Gradio UI
46
+ with gr.Blocks(title="Azure OpenAI + Redis Cloud Chat") as demo:
47
+ gr.Markdown("# 💬 Azure OpenAI + Redis Cloud Demo")
48
+ with gr.Row():
49
+ chatbot = gr.Chatbot()
50
+ with gr.Row():
51
+ msg = gr.Textbox(placeholder="Type your message here...")
52
+ send = gr.Button("Send")
53
+
54
+ def respond(message, history):
55
+ bot_reply = chat_with_ai(message)
56
+ history.append((message, bot_reply))
57
+ return history, ""
58
+
59
+ send.click(respond, [msg, chatbot], [chatbot, msg])
60
+ msg.submit(respond, [msg, chatbot], [chatbot, msg])
61
+
62
+ if __name__ == "__main__":
63
+ demo.launch(debug=True, server_name="0.0.0.0",server_port=7860,pwa=True)