allinaigc/text2sql
0
1'''21. 大模型以Qwen API形式提供。31. 重塑了Qwen作为大语言模型做Text2SQL的提示词:4 sys_prompt = """5 1. 你是一个将文字转换成SQL语句的人工智能。6 2. 你需要注意:你只需要用纯文本回复代码的内容,即你不允许回复代码以外的任何信息。7 3. SQL变量默认是中文,而且只能从如下的名称列表中选择,你不可以使用这些名字以外的变量名:"长度","宽度","价格","产品ID","比率","类别","*"8 4. 你不能写IF, THEN的SQL语句,需要使用CASE。9 5. 我需要你转换的文字如下:""" 10 11 total_prompt = sys_prompt + "在数据表格table01中," + prompt12 13 14'''15##TODO: 2. 账号功能。16 17import time18import os19import pandas as pd20import streamlit as st21from code_editor import code_editor22import streamlit_authenticator as stauth23 24# from utils.setup import setup_connexion, setup_session_state25# from utils.vanna_calls import (26# generate_questions_cached,27# run_sql_cached,28# generate_plotly_code_cached,29# generate_plot_cached,30# generate_followup_cached,31# )32# import chatsql003 ### 本地ChatGLT 版本。33import chatsql004 ###Qwen API 版本。34import sql_command35# from streamlit_pandas_profiling import st_profile_report36import dashscope37from dotenv import load_dotenv38 39 40load_dotenv()41### 设置openai的API key42dashscope.api_key = os.environ['dashscope_api_key']43 44st.set_page_config(layout="wide", page_icon="🧩", page_title="本地化国产大模型数据库查询演示")45# setup_connexion()46 47def clear_all():48 st.session_state.conversation = None49 st.session_state.chat_history = None50 st.session_state.messages = []51 message_placeholder = st.empty()52 st.session_state["my_question"] = None53 return None54## 原始的控制面板55# st.sidebar.title("大模型控制面板")56# st.sidebar.checkbox("Show SQL", value=True, key="show_sql")57# st.sidebar.checkbox("Show Table", value=True, key="show_table")58# st.sidebar.checkbox("Show Plotly Code", value=True, key="show_plotly_code")59# st.sidebar.checkbox("Show Chart", value=True, key="show_chart")60# st.sidebar.checkbox("Show Follow-up Questions", value=True, key="show_followup")61# st.sidebar.button("清除记录,重启一轮新对话", on_click=setup_session_state, use_container_width=True, type='primary')62 63st.title("本地化国产大模型数据库查询演示")64# st.title("大语言模型SQL数据库查询中心")65# st.info("声明:内容由人工智能生成,仅供参考。如果您本人使用或对外传播本服务生成的输出,您应当主动核查输出内容的真实性、准确性,避免传播虚假信息。") ## 颜色比较明显。66st.markdown("_声明:内容由人工智能生成,仅供参考。如果您本人使用或对外传播本服务生成的输出,您应当主动核查输出内容的真实性、准确性,避免传播虚假信息。_")67 68 69### authentication with a local yaml file.70import yaml71from yaml.loader import SafeLoader72with open('./config.yaml') as file:73 config = yaml.load(file, Loader=SafeLoader)74authenticator = stauth.Authenticate(75 config['credentials'],76 config['cookie']['name'],77 config['cookie']['key'],78 config['cookie']['expiry_days'],79 config['preauthorized']80)81 82user, authentication_status, username = authenticator.login('main')83# user, authentication_status, username = authenticator.login('用户登录', 'main')84print('登录的用户:', username)85 86### Streamlit Sidebar 左侧工具栏87# st.sidebar.write(st.session_state)88if authentication_status:89 90 with st.sidebar:91 st.markdown(92 """93 <style>94 [data-testid="stSidebar"][aria-expanded="true"]{95 min-width: 500px;96 max-width: 500px;97 }98 """,99 unsafe_allow_html=True,100 )101 102 # st.header(f'**大语言模型专家系统工作设定区**')103 st.header(f'**欢迎 **{username}** 使用本系统** ')104 st.write(f'_Large Language Model Expert System Working Environment_')105 # st.write(f'_Welcome and Hope U Enjoy Staying Here_')106 authenticator.logout('登出', 'sidebar')107 ### siderbar的题目。108 ### siderbar的题目。109 # st.header(f'**大语言模型专家系统工作设定区**')110 # st.header(f'**欢迎 **{username}** 使用本系统** ') ## 用户登录显示。111 st.sidebar.button("清除记录,重启一轮新对话", on_click=clear_all, use_container_width=True, type='primary')112 # st.sidebar.button("清除记录,重启一轮新对话", on_click=setup_session_state, use_container_width=True, type='primary')113 114 ### 展示当前数据库115 # st.markdown("#### 当前数据库中的数据:")116 with st.expander("#### 当前数据库中的数据", expanded=True):117 my_db = pd.read_sql_table('table01', 'sqlite:///myexcelDB.db')118 st.dataframe(my_db, width=400)119 120 ## 在sidebar上的三个分页显示,用st.tabs实现。121 tab_1, tab_2, tab_4 = st.tabs(['使用须知', '模型参数', '角色设定'])122 # tab_1, tab_2, tab_3, tab_4 = st.tabs(['使用须知', '模型参数', '提示词模板', '系统角色设定'])123 124 # with st.expander(label='**使用须知**', expanded=False):125 with tab_1:126 # st.markdown("#### 快速上手指南")127 # with st.text(body="说明"):128 # st.markdown("* 重启一轮新对话时,只需要刷新页面(按Ctrl/Command + R)即可。")129 with st.text(body="说明"):130 st.markdown("""* 简介131 132 本系统使用大模型技术,将自然语言描述转换为SQL查询语句。用户可以输入自然语言问题,系统会自动生成相应的SQL语句,并返回查询结果。133 134 * 使用步骤135 136 在文本框中输入您的自然语言问题。137 系统会自动生成相应的SQL语句,并显示在下方。138 点击“满意,请执行语句”选项,可查看查询结果。点击”不满意,需要改正语句“可以手动修改SQL语句。139 140 * 注意事项141 142 本系统仍在开发中,可能会存在一些错误或不准确的地方。143 自然语言描述越清晰,生成的SQL语句越准确。144 系统支持的SQL语法有限,请尽量使用简单易懂的语法。145 """)146 # with st.text(body="说明"):147 # st.markdown("""在构建大语言模型本地知识库问答系统时,需要注意以下几点:148 149 # LLM的选择:LLM的选择应根据系统的应用场景和需求进行。对于需要处理通用问题的系统,可以选择通用LLM;对于需要处理特定领域问题的系统,可以选择针对该领域进行微调的LLM。150 # 本地知识库的构建:本地知识库应包含系统所需的所有知识。知识的组织方式应便于LLM的访问和处理。151 # 系统的评估:系统应进行充分的评估,以确保其能够准确地回答用户问题。152 # 大语言模型本地知识库问答系统具有以下优势:153 154 # 准确性:LLM和本地知识库的结合可以提高系统的准确性。155 # 全面性:LLM和本地知识库的结合可以使系统能够回答更广泛的问题。156 # 效率:LLM可以快速生成候选答案,而本地知识库可以快速评估候选答案的准确性。157 # """)158 159 160 # with st.text(body="说明"):161 # st.markdown(162 # "* “数据分析模式”暂时只支持1000个单元格以内的数据分析,单元格中的内容不支持中文数据(表头也尽量不使用中文)。一般运行时间在1至10分钟左右,期间需要保持网络畅通。")163 # with st.text(body="说明"):164 # st.markdown("* “数据分析模式”推荐上传csv格式的文件,部分Excel文件容易出现数据不兼容的情况。")165 166 ## 大模型参数167 # with st.expander(label='**大语言模型参数**', expanded=True):168 with tab_2:169 max_tokens = st.slider(label='Max_Token(生成结果时最大字数)', min_value=100, max_value=4096, value=2048, step=100)170 temperature = st.slider(label='Temperature (温度)', min_value=0.0, max_value=1.0, value=0.8, step=0.1)171 top_p = st.slider(label='Top_P (核采样)', min_value=0.0, max_value=1.0, value=0.6, step=0.1)172 frequency_penalty = st.slider(label='Frequency Penalty (重复度惩罚因子)', min_value=-2.0, max_value=2.0, value=1.0, step=0.1)173 presence_penalty = st.slider(label='Presence Penalty (控制主题的重复度)', min_value=-2.0, max_value=2.0, value=1.0, step=0.1)174 175 ## reset password widget176 # try:177 # if authenticator.reset_password(st.session_state["username"], 'Reset password'):178 # st.success('Password modified successfully')179 # except Exception as e:180 # st.error(e)181 182 # with st.header(body="欢迎"):183 # st.markdown("# 欢迎使用大语言模型商业智能中心")184 # with st.expander(label=("**重要的使用注意事项**"), expanded=True):185 # with st.container():186 187 ##NOTE: 在SQL场景去不需要展示这些提示词。188 # with tab_3:189 # # st.markdown("#### Prompt提示词参考资料")190 # # with st.expander(label="**大语言模型基础提示词Prompt示例**", expanded=False):191 # st.code(192 # body="继续用中文写一篇关于 [文章主题] 的文章,以下列句子开头:[文章开头]。", language='plaintext')193 # st.code(body="将以下文字概括为 100 个字,使其易于阅读和理解。避免使用复杂的句子结构或技术术语。",194 # language='plaintext')195 # st.code(body="给我出一个迪奥2023春季发布会活动策划。", language='plaintext')196 # st.code(body="帮我按照正式会议结构写一个会邀:主题是xx手机游戏立项会议。", language='plaintext')197 # st.code(body="帮我写一个车内健康监测全场景落地的项目计划,用表格。", language='plaintext')198 # st.code(199 # body="同时掷两枚质地均匀的骰子,则两枚骰子向上的点数之和为 7 的概率是多少。", language='plaintext')200 # st.code(body="写一篇产品经理的演讲稿,注意使用以下词汇: 赋能,抓手,中台,闭环,落地,漏斗,沉淀,给到,同步,对齐,对标,迭代,拉通,打通,升级,交付,聚焦,倒逼,复盘,梳理,方案,联动,透传,咬合,洞察,渗透,兜底,解耦,耦合,复用,拆解。", language='plaintext')201 202 # with st.expander(label="**数据分析模式的专用提示词Prompt示例**", expanded=False):203 # # with st.subheader(body="提示词Prompt"):204 # st.code(body="分析此数据集并绘制一些'有趣的图表'。", language='python')205 # st.code(206 # body="对于这个文件中的数据,你需要要找出[X,Y]数据之间的寻找'相关性'。", language='python')207 # st.code(body="对于这个文件中的[xxx]数据给我一个'整体的分析'。", language='python')208 # st.code(body="对于[xxx]数据给我一个'直方图',提供图表,并给出分析结果。", language='python')209 # st.code(body="对于[xxx]数据给我一个'小提琴图',并给出分析结果。", language='python')210 # st.code(211 # body="对于[X,Y,Z]数据在一个'分布散点图 (stripplot)',所有的数据在一张图上展现, 并给出分析结果。", language='python')212 # st.code(body="对于[X,Y]数据,进行'T检验',你需要展示图表,并给出分析结果。",213 # language='python')214 # st.code(body="对于[X,Y]数据给我一个3个类别的'聚类分析',并给出分析结果。",215 # language='python')216 217 with tab_4:218 st.text_area(label='系统角色设定', value='你是一个人工智能,你需要回答我提出的问题,或者完成我交代的任务。你需要使用我提问的语言(如中文、英文)来回答。', height=200, label_visibility='hidden')219 220 221myavatar = "./2D.png"222 223def set_question(question):224 st.session_state["my_question"] = question225 226 227assistant_message_suggested = st.chat_message(228 "assistant", avatar=myavatar229)230 231##! 注意在填写列名时,最佳的选择是使用双引号将名字框出来。否则LLM会不认识。232if assistant_message_suggested.button("点击这里可以查看参考问题示例 ℹ️"):233 questions = [234 '你查一下长度超过10的数据有哪些?',235 '你告诉我长度超过30且宽度超过10的数据有哪些?',236 '宽度超过20且价格超过25的数据有哪些?',237 '”长度“超过10且”宽度“超过15且”类别“是”甲“的数据有哪些?',238 '长度超过10以上的价格的总和是多少?',239 '长度排名前三的产品ID和价格和长度?',240 241 ]242 st.session_state["my_question"] = None243 # questions = generate_questions_cached() ## orignal. 244 for i, question in enumerate(questions):245 time.sleep(0.05)246 button = st.button(247 question,248 on_click=set_question,249 args=(question,),250 )251 252my_question = st.session_state.get("my_question", default=None)253 254if my_question is None:255 my_question = st.chat_input(256 "请在这里提交您的查询问题",257 )258 259if my_question:260 st.session_state["my_question"] = my_question261 user_message = st.chat_message("user")262 user_message.write(f"{my_question}")263 264 # sql = generate_sql_cached(question=my_question) ## original. 核心函数。用ChatGPT输出SQL语句。265 # sql = chatsql003.main(prompt=my_question) ## 通过本地LLM输出SQL语句。266 sql = chatsql004.main(prompt=my_question) ## 通过本地LLM输出SQL语句。267 268 if sql:269 if st.session_state.get("show_sql", True):270 assistant_message_sql = st.chat_message(271 "assistant", avatar=myavatar272 )273 assistant_message_sql.code(sql, language="sql", line_numbers=True)274 275 user_message_sql_check = st.chat_message("user")276 user_message_sql_check.write(f"您是否满意上面的SQL查询语句答案?")277 with user_message_sql_check:278 happy_sql = st.radio(279 # "Happy",280 label="您的反馈:",281 options=["未决定", "满意,请执行语句", "不满意,需要改正语句"], ## 去掉第一个happy选项。282 # options=["", "yes", "no"], ## original。283 key="radio_sql",284 index=0,285 horizontal=True,286 label_visibility='visible',287 )288 289 # ## 非original。后期添加内容。Working.290 if happy_sql == "未决定":291 df = None292 st.session_state["df"] = None293 294 if happy_sql == "不满意,需要改正语句":295 st.warning(296 "请您手动修正SQL语句,按Shift + Enter提交"297 )298 sql_response = code_editor(sql, lang="sql")299 fixed_sql_query = sql_response["text"]300 301 if fixed_sql_query != "":302 # df = run_sql_cached(sql=fixed_sql_query) ## original. 核心函数。303 df = sql_command.llm_query(sql_command=fixed_sql_query)304 else:305 df = None306 307 elif happy_sql == "满意,请执行语句":308 # df = run_sql_cached(sql=sql) ## original. 核心函数。309 df = sql_command.llm_query(sql_command=sql) ## working. 310 311 else:312 df = None313 314 if df is not None:315 st.session_state["df"] = df316 317 if st.session_state.get("df") is not None:318 ## 显示查询的结果汇总信息319 # with st.container():320 query_info_describe = st.chat_message("assistant", avatar=myavatar)321 if df is not None:322 with query_info_describe:323 metric_col1, metric_col2, metric_col3, metric_col4 = st.columns(4)324 metric_col1.metric(label='查询结果中的行数', value=f"{df.shape[0]} 行", delta=None)325 metric_col2.metric(label='查询结果中的列数', value=f"{df.shape[1]} 列", delta=None)326 metric_col3.metric(label='查询结果中的单元格数', value=f"{df.size} 个", delta=None)327 metric_col4.metric(label='查询结果中的缺失值', value=f"{df.isnull().sum().sum()} 个", delta=None)328 329 if st.session_state.get("show_table", True):330 df = st.session_state.get("df")331 332 assistant_message_table = st.chat_message(333 "assistant",334 avatar=myavatar335 )336 337 ### 目前是最佳显示方式338 if len(df) > 10:339 assistant_message_table.markdown("**查询结果较多,当前只显示前10行数据**") ##TODO: 看看是否有其他更好的显示方式。340 assistant_message_table.dataframe(df.head(10), hide_index=True)341 # assistant_message_table.dataframe(df.head(100), use_container_width=True)342 else:343 assistant_message_table.dataframe(df, hide_index=True)344 # assistant_message_table.dataframe(df,use_container_width=True)345 346 ## 以下是其他datafram的显示方式,均不理想。347 # st.dataframe(df, use_container_width=True, height=100)348 349 ## streamlit AwesomeTable, Dark模式下显示有问题。可以在sidebar上显示内容。350 # from awesome_table import AwesomeTable351 # AwesomeTable(df,show_order=True, show_search=True, show_search_order_in_sidebar=True)352 # # AwesomeTable(pd.json_normalize(df))353 354 # ## 展示图形355 # # code = generate_plotly_code_cached(question=my_question, sql=sql, df=df) ## orignal. 用LLM来构建统计图表:https://github.com/vanna-ai/vanna/blob/main/src/vanna/mistral/mistral.py356 357 # if st.session_state.get("show_plotly_code", False):358 # assistant_message_plotly_code = st.chat_message(359 # "assistant",360 # avatar=myavatar,361 # )362 # assistant_message_plotly_code.code(363 # code, language="python", line_numbers=True364 # )365 366 # user_message_plotly_check = st.chat_message("user")367 # user_message_plotly_check.write(368 # f"Are you happy with the generated Plotly code?"369 # )370 # with user_message_plotly_check:371 # happy_plotly = st.radio(372 # "Happy",373 # options=["", "yes", "no"],374 # key="radio_plotly",375 # index=0,376 # )377 378 # if happy_plotly == "no":379 # st.warning(380 # "Please fix the generated Python code. Once you're done hit Shift + Enter to submit"381 # )382 # python_code_response = code_editor(code, lang="python")383 # code = python_code_response["text"]384 # elif happy_plotly == "":385 # code = None386 387 # if code is not None and code != "":388 # if st.session_state.get("show_chart", True):389 # assistant_message_chart = st.chat_message(390 # "assistant",391 # avatar=myavatar,392 # )393 # fig = generate_plot_cached(code=code, df=df)394 # if fig is not None:395 # assistant_message_chart.plotly_chart(fig)396 # else:397 # assistant_message_chart.error("I couldn't generate a chart")398 399 ## Data Visualization: Ydata_profiling (pandas_profiling)400 # from ydata_profiling import ProfileReport401 # pr = ProfileReport(df)402 # # with st.expander(label='**数据汇总信息**', expanded=False):403 # with st.container():404 # st_profile_report(pr)405 # # st.stop()406 407 ## 数据可视化内容,高级版。408 ## pywalker: https://github.com/Kanaries/pygwalker/tree/main409 user_message_plot_check = st.chat_message("user")410 user_message_plot_check.write(f"您是否希望基于上述查询结果进行数据可视化?")411 with user_message_plot_check:412 happy_plot = st.radio(413 # "Happy",414 label="您的反馈:",415 options=["未决定", "是,需要进行数据可视化", "否,不需要进行数据可视化"], ## 去掉第一个happy选项。416 # options=["", "yes", "no"], ## original。417 key="radio_plot",418 index=0,419 horizontal=True,420 label_visibility='visible',421 )422 423 if happy_plot == "是,需要进行数据可视化":424 import pygwalker as pyg425 import streamlit.components.v1 as components426 import streamlit as st427 from pygwalker.api.streamlit import init_streamlit_comm, get_streamlit_html428 429 # Initialize pygwalker communication430 init_streamlit_comm()431 432 # When using `use_kernel_calc=True`, you should cache your pygwalker html, if you don't want your memory to explode433 @st.cache_resource434 def get_pyg_html(df: pd.DataFrame) -> str:435 # When you need to publish your application, you need set `debug=False`,prevent other users to write your config file.436 # If you want to use feature of saving chart config, set `debug=True`437 html = get_streamlit_html(df, spec="./gw0.json", use_kernel_calc=True, debug=False)438 return html439 # walker = pyg.walk(df)440 components.html(get_pyg_html(df), width=1200, height=800, scrolling=True)441 442 443 ### streamlit echarts: https://github.com/andfanilo/streamlit-echarts444 # from streamlit_echarts import st_echarts445 # from streamlit_echarts import st_pyecharts446 447 # st_pyecharts(df)448 449 450 451 452 ### Follow-up questions session. 453 # if st.session_state.get("show_followup", True):454 # assistant_message_followup = st.chat_message(455 # "assistant",456 # avatar=myavatar,457 # )458 # followup_questions = generate_followup_cached(459 # question=my_question, df=df460 # )461 # st.session_state["df"] = None462 463 # if len(followup_questions) > 0:464 # assistant_message_followup.text(465 # "Here are some possible follow-up questions"466 # )467 # # Print the first 5 follow-up questions468 # for question in followup_questions[:5]:469 # time.sleep(0.05)470 # assistant_message_followup.write(question)471 472 else:473 assistant_message_error = st.chat_message(474 "assistant", avatar=myavatar475 )476 assistant_message_error.error("我无法回答您的问题,请重新提问,谢谢!")477 