binqiangliu's picture
Update app.py
28e2d36
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)
#这两个失败的原因是因为其中使用了st.chat_message、st.markdown等st命令,而将其部署到Render的时候,使用的是gunicorn newAIChatAPI:app命令,没有streamlit run,所以会导致这些命令无法执行
#自然程序就不会有输出结果了!因此会遇到这个问题:JSONDecodeError: Expecting value: line 1 column 1 (char 0);<Response [500]>或<Response [404]>
#所以如果希望部署具有记忆功能的AI Chatbot并通过API调用,则设置为API的程序,不能够使用streamlit的具体功能!!!(即其命令执行中不能够使用st的功能!)
#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是内置词,不得修改;如果调用API成功,response的值为<Response [200]>
#上面这行代码的意思就是,使用post方式调用API,API的路径是url,输入给API的json数据由json_data_for_api赋值(然后在API端,json中的键值会被user_query = data['user_question']提取出来)
result = response.json()
#result的形似类似于:{'response': "I'm happy... else I can assist you with?"}
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的响应