alapl063 commited on
Commit
b7fea89
·
verified ·
1 Parent(s): 5ec14a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -53
app.py CHANGED
@@ -5,64 +5,107 @@ import langdetect
5
  import requests
6
  import random
7
 
8
-
9
  GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- client = Groq(api_key=os.getenv("GROQ_API_KEY"))
 
 
 
 
 
 
 
12
 
 
 
 
 
13
 
14
- def respond(
15
- message,
16
- history: list[tuple[str, str]],
17
- system_message,
18
- max_tokens,
19
- temperature,
20
- top_p,
21
- ):
22
- messages = [{"role": "system", "content": system_message}]
23
 
24
- for val in history:
25
- if val[0]:
26
- messages.append({"role": "user", "content": val[0]})
27
- if val[1]:
28
- messages.append({"role": "assistant", "content": val[1]})
29
 
 
 
30
  messages.append({"role": "user", "content": message})
31
 
32
- response = ""
33
-
34
- for message in client.chat_completion(
35
- messages,
36
- max_tokens=max_tokens,
37
- stream=True,
38
- temperature=temperature,
39
- top_p=top_p,
40
- ):
41
- token = message.choices[0].delta.content
42
-
43
- response += token
44
- yield response
45
-
46
-
47
- """
48
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
49
- """
50
- demo = gr.ChatInterface(
51
- respond,
52
- additional_inputs=[
53
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
54
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
55
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
56
- gr.Slider(
57
- minimum=0.1,
58
- maximum=1.0,
59
- value=0.95,
60
- step=0.05,
61
- label="Top-p (nucleus sampling)",
62
- ),
63
- ],
64
- )
65
-
66
-
67
- if __name__ == "__main__":
68
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  import requests
6
  import random
7
 
8
+ # Load API Key
9
  GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
10
+ client = Groq(api_key=GROQ_API_KEY)
11
+
12
+ # Detect Language
13
+ def detect_language(text):
14
+ try:
15
+ lang = langdetect.detect(text)
16
+ return "fr" if lang == "fr" else "en"
17
+ except:
18
+ return "en"
19
+
20
+ # Function to search for reservation links
21
+ def find_reservation_link(query):
22
+ search_url = f"https://www.googleapis.com/customsearch/v1?q={query}+booking&key=your_google_api_key&cx=your_custom_search_engine_id"
23
+ response = requests.get(search_url)
24
+ data = response.json()
25
+
26
+ if "items" in data and len(data["items"]) > 0:
27
+ return data["items"][0]["link"]
28
+
29
+ return "I couldn't find a link for that. Try searching manually."
30
 
31
+ # Button Click Handler
32
+ def handle_button_click(button_text):
33
+ options = {
34
+ "Trip recommendations": "What are the top travel spots right now?",
35
+ "Send me somewhere!": f"Pick a place for me. Maybe {random.choice(['Paris', 'Tokyo', 'New York', 'Barcelona', 'Rome', 'Bali', 'Dubai', 'Sydney'])}!",
36
+ "1 week planned vacations": "Plan a 1-week trip for me."
37
+ }
38
+ return options.get(button_text, "")
39
 
40
+ # Chat Function with Memory
41
+ def chat_with_bot(message, history):
42
+ # Ensure history is correctly formatted
43
+ history = history or [{"role": "assistant", "content": "Hey! I'm FlightAI. How can I help with your travel plans?"}]
44
 
45
+ # If button text was used
46
+ if message in ["Trip recommendations", "Send me somewhere!", "1 week planned vacations"]:
47
+ message = handle_button_click(message)
48
+
49
+ # Detect language
50
+ language = detect_language(message)
 
 
 
51
 
52
+ system_message = {
53
+ "en": "You help users plan trips. Keep responses short and clear. If a user asks about booking a flight, hotel, or reservation, try to find a link.",
54
+ "fr": "Vous aidez les utilisateurs à planifier des voyages. Réponses courtes et simples. Si un utilisateur demande une réservation, fournissez un lien."
55
+ }
 
56
 
57
+ # Format history for chat completion
58
+ messages = [{"role": "system", "content": system_message[language]}] + history
59
  messages.append({"role": "user", "content": message})
60
 
61
+ # Check for reservation-related queries
62
+ if any(keyword in message.lower() for keyword in ["book a flight", "hotel reservation", "car rental", "book a room"]):
63
+ link = find_reservation_link(message)
64
+ return history + [{"role": "assistant", "content": f"Here's a link that might help: {link}"}]
65
+
66
+ # Call AI model
67
+ response = client.chat.completions.create(
68
+ model="llama-3.3-70b-versatile",
69
+ messages=messages,
70
+ temperature=0.7,
71
+ max_tokens=1024,
72
+ top_p=1
73
+ )
74
+
75
+ bot_reply = response.choices[0].message.content
76
+ history.append({"role": "user", "content": message})
77
+ history.append({"role": "assistant", "content": bot_reply})
78
+
79
+ return history
80
+
81
+ # Gradio Interface
82
+ with gr.Blocks(css="""
83
+ body { background-color: #A9B5DF; }
84
+ .gradio-container { background-color: #A9B5DF; }
85
+ .gradio-markdown { background-color: #2D336B; color: white; padding: 10px; border-radius: 10px; }
86
+ .gradio-button { background-color: #7886C7; color: white; border-radius: 10px; }
87
+ .gradio-chatbot-message { background-color: #FFF2F2; color: #2D336B; padding: 10px; border-radius: 10px; }
88
+ """) as demo:
89
+ gr.Markdown("# 🌍 ***FlightAI - Your Travel Assistant - Votre Assistant de Voyage*** ✈️\n")
90
+
91
+ chatbot = gr.Chatbot(type="messages", value=[
92
+ {"role": "assistant", "content": "Hey! I'm FlightAI. Tell me your travel plans or pick a button below!"}
93
+ ])
94
+
95
+ with gr.Row():
96
+ btn1 = gr.Button("Trip recommendations")
97
+ btn2 = gr.Button("Send me somewhere!")
98
+ btn3 = gr.Button("1 week planned vacations")
99
+
100
+ user_input = gr.Textbox(placeholder="Type your travel question here...")
101
+
102
+ # Button Click Event Handling
103
+ def button_click(btn_text):
104
+ return chat_with_bot(btn_text, chatbot.value)
105
+
106
+ btn1.click(button_click, inputs=[btn1], outputs=[chatbot])
107
+ btn2.click(button_click, inputs=[btn2], outputs=[chatbot])
108
+ btn3.click(button_click, inputs=[btn3], outputs=[chatbot])
109
+ user_input.submit(chat_with_bot, inputs=[user_input, chatbot], outputs=[chatbot])
110
+
111
+ demo.launch()