-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
60 lines (49 loc) · 2.06 KB
/
Copy pathapp.py
File metadata and controls
60 lines (49 loc) · 2.06 KB
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
import streamlit as st
import urllib.request
import json
from config import *
st.title("AI Chatbot")
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Get user input
if query := st.chat_input("Enter your message"):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": query})
with st.chat_message("user"):
st.markdown(query)
# Prepare the API request
data = {"chat_input": query}
body = str.encode(json.dumps(data))
url = AZURE_PROMPT_FLOW_RAG_ENDPOINT
api_key = AZURE_PROMPT_FLOW_RAG_API_KEY
if not api_key:
st.error("API key is required")
else:
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + api_key,
'azureml-model-deployment': AZURE_PROMPT_FLOW_RAG_DEPLOYMENT_NAME
}
# Show the assistant's response
with st.chat_message("assistant"):
message_placeholder = st.empty()
try:
req = urllib.request.Request(url, body, headers)
response = urllib.request.urlopen(req)
result = response.read()
result_string = result.decode('utf-8')
result_json = json.loads(result_string)
# Display the response
assistant_response = result_json["chat_output"]
message_placeholder.markdown(assistant_response)
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": assistant_response})
except urllib.error.HTTPError as error:
message_placeholder.error(f"Request failed with status code: {error.code}\n{error.info()}")
except Exception as e:
message_placeholder.error(f"An error occurred: {str(e)}")