notjulietxd commited on
Commit
6bf2192
·
verified ·
1 Parent(s): c1616d5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -0
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import json
4
+ import os
5
+
6
+ # Set page config
7
+ st.set_page_config(page_title="Military Plaques Chat Assistant", page_icon="📛")
8
+
9
+
10
+
11
+
12
+ # Set up session state for chat history
13
+ if "messages" not in st.session_state:
14
+ st.session_state.messages = [{"role": "assistant", "content": "Hi! I'm the Military Plaques AI assistant. How can I help you today?"}]
15
+
16
+ # Flowise API configuration
17
+ FLOWISE_URL = os.getenv("FLOWISE_URL")
18
+ FLOWISE_API_KEY = FLOWISE_URL
19
+
20
+ def get_flowise_response(prompt):
21
+ """Get response from Flowise API"""
22
+ headers = {
23
+ "Authorization": f"Bearer {FLOWISE_API_KEY}",
24
+ "Content-Type": "application/json"
25
+ }
26
+
27
+ # Send only role and content in history
28
+ payload = {
29
+ "question": prompt,
30
+ "history": [{"role": m["role"], "content": m["content"]} for m in st.session_state.messages]
31
+ }
32
+
33
+ try:
34
+ response = requests.post(FLOWISE_URL, headers=headers, json=payload)
35
+ response.raise_for_status()
36
+ return response.json()
37
+ except requests.exceptions.RequestException as e:
38
+ return {"error": f"API request failed: {str(e)}"}
39
+ except json.JSONDecodeError:
40
+ return {"error": "Invalid JSON response from API"}
41
+
42
+ # Display chat messages
43
+ for index, message in enumerate(st.session_state.messages):
44
+ with st.chat_message(message["role"]):
45
+ st.markdown(message["content"])
46
+
47
+ # Display sources if available
48
+ if message["role"] == "assistant":
49
+ sources = message.get("sources", [])
50
+ if sources:
51
+ st.markdown("**References:**")
52
+ for idx, source in enumerate(sources, 1):
53
+ st.markdown(f"{idx}. {source}")
54
+ else:
55
+ pass
56
+
57
+
58
+
59
+ # Starter prompts
60
+ starter_prompts = [
61
+ "What types of plaques do you offer?",
62
+ "Can I customize my plaque design?",
63
+ "How long does it take to receive my order?",
64
+ "Contact details"
65
+ ]
66
+
67
+ # Show starter buttons only if no user input yet
68
+ if len(st.session_state.messages) == 1:
69
+ cols = st.columns(2)
70
+ for i, prompt in enumerate(starter_prompts):
71
+ with cols[i % 2]:
72
+ if st.button(prompt):
73
+ # Add user message
74
+ st.session_state.messages.append({"role": "user", "content": prompt})
75
+
76
+ # Get response
77
+ with st.spinner("Thinking..."):
78
+ flowise_response = get_flowise_response(prompt)
79
+
80
+ if "error" in flowise_response:
81
+ response_content = f"Error: {flowise_response['error']}"
82
+ sources = []
83
+ follow_up_prompts = []
84
+ else:
85
+ response_content = flowise_response.get("text", "Sorry, I didn't get that.")
86
+
87
+ # Extract unique sources
88
+ source_docs = flowise_response.get("sourceDocuments", [])
89
+ sources = list(set(
90
+ doc.get("metadata", {}).get("source", "")
91
+ for doc in source_docs
92
+ ))
93
+ sources = [s for s in sources if s] # Remove empty strings
94
+
95
+ # Parse follow-up prompts
96
+ follow_up_str = flowise_response.get("followUpPrompts", "[]")
97
+ try:
98
+ # Handle double-encoded JSON string
99
+ parsed = json.loads(follow_up_str)
100
+ if isinstance(parsed, str):
101
+ follow_up_prompts = json.loads(parsed)
102
+ else:
103
+ follow_up_prompts = parsed
104
+ except json.JSONDecodeError:
105
+ follow_up_prompts = []
106
+
107
+ # Add assistant response
108
+ st.session_state.messages.append({
109
+ "role": "assistant",
110
+ "content": response_content,
111
+ "sources": sources,
112
+ "follow_up_prompts": follow_up_prompts
113
+ })
114
+ st.rerun()
115
+
116
+ # Handle user input
117
+ if prompt := st.chat_input("Type your message here..."):
118
+ # Add user message
119
+ st.session_state.messages.append({"role": "user", "content": prompt})
120
+
121
+ # Get response
122
+ with st.chat_message("assistant"):
123
+ with st.spinner("Thinking..."):
124
+ flowise_response = get_flowise_response(prompt)
125
+
126
+ if "error" in flowise_response:
127
+ response_content = f"Error: {flowise_response['error']}"
128
+ sources = []
129
+ follow_up_prompts = []
130
+ else:
131
+ response_content = flowise_response.get("text", "Sorry, I didn't get that.")
132
+
133
+ # Extract unique sources
134
+ source_docs = flowise_response.get("sourceDocuments", [])
135
+ sources = list(set(
136
+ doc.get("metadata", {}).get("source", "")
137
+ for doc in source_docs
138
+ ))
139
+ sources = [s for s in sources if s] # Remove empty strings
140
+
141
+ # Parse follow-up prompts
142
+ follow_up_str = flowise_response.get("followUpPrompts", "[]")
143
+ try:
144
+ # Handle double-encoded JSON string
145
+ parsed = json.loads(follow_up_str)
146
+ if isinstance(parsed, str):
147
+ follow_up_prompts = json.loads(parsed)
148
+ else:
149
+ follow_up_prompts = parsed
150
+ except json.JSONDecodeError:
151
+ follow_up_prompts = []
152
+
153
+ # Display response
154
+ st.markdown(response_content)
155
+
156
+ # Display sources
157
+ if sources:
158
+ st.markdown("**References:**")
159
+ for idx, source in enumerate(sources, 1):
160
+ st.markdown(f"{idx}. {source}")
161
+ else:
162
+ pass
163
+
164
+
165
+ # Add assistant response to history
166
+ st.session_state.messages.append({
167
+ "role": "assistant",
168
+ "content": response_content,
169
+ "sources": sources,
170
+ "follow_up_prompts": follow_up_prompts
171
+ })