binqiangliu's picture
Update app.py
e865af2
raw
history blame
2.02 kB
import requests
import streamlit as st
def call_chatbot_api(query):
# url = 'https://hf-aichat-api.onrender.com/api/chat' #OKed
url = 'https://hf-aichatboapi.onrender.com/api/chat' #Failed
# url = 'https://newaichatapi.onrender.com/api/chat' #Failed: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
#data = {'query': query}
#在API设置中,将#user_query = data['query']中的query修改为user_question,因此在此处的API调用代码中,需要相应的使用data = {'user_question': query}
json_data_for_api = {'user_question': query}
#data sample示例: {'query': 'Hello'},这个就是json格式,然后,这个data将作为json传递给API(在API设置的data = request.get_json()中被提取并赋值给data)
#这个API调用程序代码,首先是为API准备数据,并且是json格式的
response = requests.post(url, json=json_data_for_api) #json=...这里的json是内置词,不得修改
#上面这行代码的意思就是,使用post方式调用API,API的路径是url,输入给API的json数据由json_data_for_api赋值(然后在API端,json中的键值会被user_query = data['user_question']提取出来)
result = response.json()
return result['response']
#提取json数据中某个键的键值,就是使用json['key_name']的方式,这样获得的,就是key_name对应的键值(字符串?)
#此外,这里使用的是result['response'],是因为在API设置代码中使用的是 return jsonify({'response': initial_response}),其中key_name是response
user_query = st.text_input("Enter your query here:")
with st.spinner("AI Thinking...Please wait a while to Cheers!"):
if user_query !="" and not user_query.strip().isspace() and not user_query == "" and not user_query.strip() == "" and not user_query.isspace():
response = call_chatbot_api(user_query)
st.write("AI Response:")
st.write(response)
print(response) # 打印Chatbot的响应