赞
踩
Streamlit是时下比较热门的一个基于Python的Web应用程序框架,它可以在几分钟内将数据转化为可共享的Web应用程序,无需前端开发经验,使用纯Python代码实现,简单且高效。ChatGPT是目前非常火的OpenAI公司开发的聊天机器人模型,它无所不知就像一本大百科全书,它可以帮你做很多繁杂的日常工作,比如可以代你写文章,代你做excel表格,甚至代你写代码。今天我们要将两者结合起来开发一个基于web的应用聊天小程序。
我们需要在python环境中安装openai和streamlit的第三方python包,可以通过在命令行窗口中安装这些包:
- pip install openai
- pip install streamlit
- pip install streamlit_chat
我们需要创建一个用于聊天的streamlit的代码文件 chat_bot.py:
- # chat_bot.py
-
- import openai
- import streamlit as st
- from streamlit_chat import message
-
- #申请的api_key
- openai.api_key = "xxxxxxxxxxxxxxxxx"
- def generate_response(prompt):
- completion=openai.Completion.create(
- model='text-davinci-003',
- prompt=prompt,
- max_tokens=1024,
- temperature=0.6
- )
- message=completion.choices[0].text
- return message
-
- st.markdown("#### 我是ChatGPT聊天机器人,我可以回答您的任何问题!")
- if 'generated' not in st.session_state:
- st.session_state['generated'] = []
- if 'past' not in st.session_state:
- st.session_state['past'] = []
- user_input=st.text_input("请输入您的问题:",key='input')
- if user_input:
- output=generate_response(user_input)
- st.session_state['past'].append(user_input)
- st.session_state['generated'].append(output)
- if st.session_state['generated']:
- for i in range(len(st.session_state['generated'])-1, -1, -1):
- message(st.session_state["generated"][i], key=str(i))
- message(st.session_state['past'][i],
- is_user=True,
- key=str(i)+'_user')

我们需要在命令行窗口执行启动streamlit的命令:
streamlit run chat_bot.py
输入启动streamlit命令后,会弹出浏览器, 如果没有弹出浏览器可以自行打开浏览器并输入上图中的url地址,接下来就可以开始和ChatGPT聊天了:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。