# ChatGPT实战(六):搭建AI对话网站(OpenAI API + streamit)

作者:华王
星球:https://t.zsxq.com/0dgMjetVg (opens new window)

学习、分享、成功;提高效率,有所收获!😄

分享一个ChatGPT与Streamlit的结合的案例,搭建一个简单的网页版对话demo

可能用的人太多,没加载出来哈哈

streamlit是一个python库,可以使用纯python搭建一个网页,通过调用openai的api,创建一个网页版的简单对话模型

准备

pip install openai 
pip install streamlit #安装相关库
https://openai.com/api/ #申请key
streamlit run page_openai.py #启动命令
1
2
3
4

代码展示


import openai
import streamlit as st
from streamlit.elements.image import image_to_url
# st.set_page_config(page_icon="🌴", page_title="ChatGPT", layout="wide")
st.set_page_config(page_title="ChatGPT", page_icon="🤖")  #设置网页标签和icon
image_url = image_to_url("data/white.jpg", width=-3, clamp=False, channels="RGB", output_format="auto", image_id="", allow_emoji=False) #设置背景图片
st.markdown('''
    <style>
        .css-fg4pbf {background-image:url(''' + image_url + ''');}
    </style>
''', unsafe_allow_html = True)

# openai.api_key = "请输入你从OpenAI网站获取的key"
def get_response(prompt):
    # request = openai.Completion.create(
    #     engine = 'text-davinci-003',
    #     prompt = prompt,
    #     max_tokens = 1024,
    #     top_p = 1,
    #     stop = None,
    #     temperature=0.2,
    # )

    chat = openai.Completion.create(
        model="gpt-3.5-turbo", #engine代表使用的训练模型
        temperature=0.6, #置信度,数值一般设置为0.6
        max_tokens=3000, #可以返回的最大字符数
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0,
        messages=[
            {"role": "system", "content": "You are a useful assistant."},
            {"role": "user", "content": prompt}
        ]
    )
    print(chat)
    reply = chat.choices[0].message.content
    print(f"ChatGPT: {reply}")
    return reply

st.markdown(f'<p style="background-image: linear-gradient(to right, #ff1a1a, #ff8080 ,#ffffff);background-color:;color:white;font-size:24px;border-radius:1rem;">与OpenAI推出的ChatGPT进行对话</p', unsafe_allow_html=True)
user_input = st.empty().text_input(label="请输入你要提问的问题, 输入完成后按回车键提交!")
record = []
if len(user_input) > 0:
    with st.spinner("请稍后,机器人🤖正在准备答案"):
        st.info(get_response(user_input))
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

启动

streamlit run page_openai.py #启动命令

说明: 1、chatgpt在许多地域尚不能直接使用,需额外做一些配置才能使用,具体方法可联系小编 2、当问的问题比较复杂或描述不够准确时,chatgpt也会返回不规范或意料之外的答案。 3、chatgpt的响应速度不是很快,优点是没有了浏览器里搜索引擎打来的一系列广告

上次更新: 2023/6/18