├── .devcontainer └── devcontainer.json ├── .matplotlib ├── .matplotlibrc └── fonts │ └── SimHei.ttf ├── .streamlit └── config.toml ├── Home.py ├── LICENSE.txt ├── README.md ├── docs └── images │ ├── screen2.png │ ├── screen3.png │ ├── short1.png │ └── short2.png ├── llm ├── __init__.py └── ais_erniebot.py ├── middleware ├── __init__.py └── base.py ├── parser ├── __init__.py └── response_parser.py ├── requirements.txt └── util.py /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Python 3", 3 | // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile 4 | "image": "mcr.microsoft.com/devcontainers/python:1-3.11-bullseye", 5 | "customizations": { 6 | "codespaces": { 7 | "openFiles": [ 8 | "README.md", 9 | "Home.py" 10 | ] 11 | }, 12 | "vscode": { 13 | "settings": {}, 14 | "extensions": [ 15 | "ms-python.python", 16 | "ms-python.vscode-pylance" 17 | ] 18 | } 19 | }, 20 | "updateContentCommand": "[ -f packages.txt ] && sudo apt update && sudo apt upgrade -y && sudo xargs apt install -y None: 40 | self.agent = None 41 | self.id = str(uuid.uuid4()) 42 | 43 | def get_llm(self): 44 | op = st.session_state.last_option 45 | llm = None 46 | if op == "Ollama": 47 | llm = get_ollama_model(st.session_state.ollama_model, st.session_state.ollama_base_url) 48 | elif op == "OpenAI": 49 | if st.session_state.api_token != "": 50 | llm = get_open_ai_model(st.session_state.api_token) 51 | elif op == "Baidu/AIStudio-Ernie-Bot": 52 | if st.session_state.access_token != "": 53 | llm = get_baidu_as_model(st.session_state.access_token) 54 | elif op == "Baidu/Qianfan-Ernie-Bot": 55 | if st.session_state.client_id != "" and st.session_state.client_secret != "": 56 | llm = get_baidu_qianfan_model(st.session_state.client_id, st.session_state.client_secret) 57 | if llm is None: 58 | st.toast("LLM initialization failed, check LLM configuration", icon="🫤") 59 | return llm 60 | 61 | def set_file_data(self, df): 62 | llm = self.get_llm() 63 | if llm is not None: 64 | print("llm.type", llm.type) 65 | config = Config( 66 | llm=llm, 67 | callback=StdoutCallback(), 68 | # middlewares=[CustomChartsMiddleware()], 69 | response_parser=CustomResponseParser, 70 | custom_prompts={ 71 | "generate_python_code": get_prompt_template() 72 | }, 73 | enable_cache=False, 74 | verbose=True 75 | ) 76 | self.agent = Agent(df, config=config, memory_size=memory_size) 77 | self.agent._lake.add_middlewares(CustomChartsMiddleware()) 78 | st.session_state.llm_ready = True 79 | 80 | def chat(self, prompt): 81 | if self.agent is None: 82 | st.toast("LLM initialization failed, check LLM configuration", icon="🫣") 83 | st.stop() 84 | else: 85 | return self.agent.chat(prompt) 86 | 87 | def start_new_conversation(self): 88 | self.agent.start_new_conversation() 89 | st.session_state.chat_history = [] 90 | 91 | 92 | @st.cache_resource 93 | def get_agent(agent_id) -> AgentWrapper: 94 | agent = AgentWrapper() 95 | return agent 96 | 97 | chat_history_key = "chat_history" 98 | if chat_history_key not in st.session_state: 99 | st.session_state[chat_history_key] = [] 100 | 101 | 102 | if "llm_ready" not in st.session_state: 103 | st.session_state.llm_ready = False 104 | 105 | # Description 106 | tab1, tab2 = st.tabs(["Workspace", "Screenshots"]) 107 | with tab2: 108 | col1, col2 = st.columns(2) 109 | with col1: 110 | st.image("docs/images/short1.png") 111 | with col2: 112 | st.image("docs/images/short2.png") 113 | 114 | # DataGrid 115 | with st.expander("DataGrid Content") as ep: 116 | grid = st.dataframe(pd.DataFrame(), use_container_width=True) 117 | counter = st.markdown("") 118 | 119 | # Sidebar layout 120 | with st.sidebar: 121 | option = st.selectbox("Choose LLM", ["OpenAI", "Baidu/AIStudio-Ernie-Bot", "Baidu/Qianfan-Ernie-Bot", "Ollama"]) 122 | 123 | # Initialize session keys 124 | if "api_token" not in st.session_state: 125 | st.session_state.api_token = "" 126 | if "access_token" not in st.session_state: 127 | st.session_state.access_token = "" 128 | if "ollama_model" not in st.session_state: 129 | st.session_state.ollama_model = "" 130 | if "ollama_base_url" not in st.session_state: 131 | st.session_state.ollama_base_url = "" 132 | if "client_id" not in st.session_state: 133 | st.session_state.client_id = "" 134 | if "client_secret" not in st.session_state: 135 | st.session_state.client_secret = "" 136 | 137 | # Initialize model configration panel 138 | if option == "OpenAI": 139 | api_token = st.text_input("API Token", st.session_state.api_token, type="password", placeholder="Api token") 140 | elif option == "Baidu/AIStudio-Ernie-Bot": 141 | access_token = st.text_input("Access Token", st.session_state.access_token, type="password", 142 | placeholder="Access token") 143 | elif option == "Baidu/Qianfan-Ernie-Bot": 144 | client_id = st.text_input("Client ID", st.session_state.client_id, placeholder="Client ID") 145 | client_secret = st.text_input("Client Secret", st.session_state.client_secret, type="password", 146 | placeholder="Client Secret") 147 | elif option == "Ollama": 148 | ollama_model = st.selectbox( 149 | "Choose Ollama Model", 150 | ["starcoder:7b", "codellama:7b-instruct-q8_0", "zephyr:7b-alpha-q8_0"] 151 | ) 152 | ollama_base_url = st.text_input("Ollama BaseURL", st.session_state.ollama_base_url, 153 | placeholder="http://localhost:11434") 154 | 155 | memory_size = st.selectbox("Memory Size", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], index=9) 156 | 157 | if st.button("+ New Chat"): 158 | st.session_state.llm_ready = False 159 | st.session_state[chat_history_key] = [] 160 | 161 | # Validation 162 | info = st.markdown("") 163 | if option == "OpenAI": 164 | if not api_token: 165 | info.error("Invalid API Token") 166 | if api_token != st.session_state.api_token: 167 | st.session_state.api_token = api_token 168 | st.session_state.llm_ready = False 169 | elif option == "Baidu/AIStudio-Ernie-Bot": 170 | if not access_token: 171 | info.error("Invalid Access Token") 172 | if access_token != st.session_state.access_token: 173 | st.session_state.access_token = access_token 174 | st.session_state.llm_ready = False 175 | elif option == "Baidu/Qianfan-Ernie-Bot": 176 | if client_id != st.session_state.client_id: 177 | st.session_state.client_id = client_id 178 | st.session_state.llm_ready = False 179 | if client_secret != st.session_state.client_secret: 180 | st.session_state.client_secret = client_secret 181 | st.session_state.llm_ready = False 182 | elif option == "Ollama": 183 | if ollama_model != st.session_state.ollama_model: 184 | st.session_state.ollama_model = ollama_model 185 | st.session_state.llm_ready = False 186 | if ollama_base_url != st.session_state.ollama_base_url: 187 | st.session_state.ollama_base_url = ollama_base_url 188 | st.session_state.llm_ready = False 189 | 190 | if "last_option" not in st.session_state: 191 | st.session_state.last_option = None 192 | 193 | if option != st.session_state.last_option: 194 | st.session_state.last_option = option 195 | st.session_state.llm_ready = False 196 | 197 | if "last_memory_size" not in st.session_state: 198 | st.session_state.last_memory_size = None 199 | 200 | if memory_size != st.session_state.last_memory_size: 201 | st.session_state.last_memory_size = memory_size 202 | st.session_state.llm_ready = False 203 | 204 | logger.log(f"st.session_state.llm_ready={st.session_state.llm_ready}", level=logging.INFO) 205 | 206 | if not st.session_state.llm_ready: 207 | st.session_state.agent_id = str(uuid.uuid4()) 208 | 209 | with st.sidebar: 210 | st.divider() 211 | file = st.file_uploader("Upload File", type=["xlsx", "csv"]) 212 | if file is None: 213 | st.session_state.uploaded = False 214 | if st.session_state.llm_ready: 215 | get_agent(st.session_state.agent_id).start_new_conversation() 216 | 217 | if "last_file" not in st.session_state: 218 | st.session_state.last_file = None 219 | 220 | if file is not None: 221 | file_obj = io.BytesIO(file.getvalue()) 222 | file_ext = Path(file.name).suffix.lower() 223 | if file_ext == ".csv": 224 | df = pd.read_csv(file_obj) 225 | else: 226 | df = pd.read_excel(file_obj) 227 | grid.dataframe(df) 228 | counter.info("Total: **%s** records" % len(df)) 229 | 230 | if file != st.session_state.last_file or st.session_state.llm_ready is False: 231 | # if not st.session_state.llm_ready: 232 | st.session_state.agent_id = str(uuid.uuid4()) 233 | get_agent(st.session_state.agent_id).set_file_data(df) 234 | 235 | st.session_state.last_file = file 236 | 237 | with st.sidebar: 238 | st.markdown(""" 239 | 268 |
269 | Share & Talk w/ me 270 |
271 | """, unsafe_allow_html=True) 272 | 273 | # ChatBox layout 274 | 275 | for item in st.session_state.chat_history: 276 | with st.chat_message(item["role"]): 277 | if "type" in item and item["type"] == "plot": 278 | tmp = st.image(item['content']) 279 | elif "type" in item and item["type"] == "dataframe": 280 | tmp = st.dataframe(item['content']) 281 | else: 282 | st.markdown(item["content"]) 283 | 284 | prompt = st.chat_input("Input the question here") 285 | if prompt is not None: 286 | st.chat_message("user").markdown(prompt) 287 | st.session_state.chat_history.append({"role": "user", "content": prompt}) 288 | with st.chat_message("assistant"): 289 | if not st.session_state.llm_ready: 290 | response = "Please upload the file and configure the LLM well first" 291 | st.markdown(response) 292 | st.session_state.chat_history.append({"role": "assistant", "content": response}) 293 | else: 294 | tmp = st.markdown(f"Analyzing, hold on pls...") 295 | 296 | response = get_agent(st.session_state.agent_id).chat(prompt) 297 | 298 | if isinstance(response, SmartDataframe): 299 | tmp.dataframe(response.dataframe) 300 | st.session_state.chat_history.append( 301 | {"role": "assistant", "content": response.dataframe, "type": "dataframe"}) 302 | elif isinstance(response, Dict) and "type" in response and response["type"] == "plot": 303 | tmp.image(f"{response['value']}") 304 | st.session_state.chat_history.append( 305 | {"role": "assistant", "content": response["value"], "type": "plot"}) 306 | else: 307 | tmp.markdown(response) 308 | st.session_state.chat_history.append({"role": "assistant", "content": response}) 309 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExcelChat 2 | ExcelChat is a AI powered app built on [pandas-ai](https://github.com/gventuri/pandas-ai) and [streamlit](https://github.com/streamlit/streamlit). Upload an excel file, then you can chat with it like chatGPT. 3 | 4 | Currently the following models are supported. 5 | * OpenAI 6 | * Ollama: starcoder:7b, codellama:7b-instruct-q8_0, zephyr:7b-alpha-q8_0 7 | * Baidu/AIStudio-Ernie-Bot, baidu ernie-bot model for ai studio (single thread mode, not suitable for multi-tenant usage) 8 | * Baidu/Qianfan-Ernie-Bot, the recommended way to use baidu ernie bot model 9 | 10 | Here are some screenshot. 11 | 12 | ![Screenshot1](docs/images/screen1.png?raw=true) 13 | ![Screenshot2](docs/images/screen2.png?raw=true) 14 | ![Screenshot3](docs/images/screen3.png?raw=true) 15 | 16 | ## Demo 17 | https://excelchat.streamlit.app 18 | 19 | ## Requirements 20 | Python >= 3.9. 21 | 22 | ## Quick Install 23 | ```shell 24 | pip install -r requirements.txt 25 | ``` 26 | ## Run 27 | Run the following command in the terminal, then you will get the app's link opened in the browser. 28 | ```shell 29 | streamlit run Home.py 30 | ``` 31 | -------------------------------------------------------------------------------- /docs/images/screen2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerlin/excelchat-streamlit/8f40b050a4560575f2bfbc5b36ca062cf165e718/docs/images/screen2.png -------------------------------------------------------------------------------- /docs/images/screen3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerlin/excelchat-streamlit/8f40b050a4560575f2bfbc5b36ca062cf165e718/docs/images/screen3.png -------------------------------------------------------------------------------- /docs/images/short1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerlin/excelchat-streamlit/8f40b050a4560575f2bfbc5b36ca062cf165e718/docs/images/short1.png -------------------------------------------------------------------------------- /docs/images/short2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerlin/excelchat-streamlit/8f40b050a4560575f2bfbc5b36ca062cf165e718/docs/images/short2.png -------------------------------------------------------------------------------- /llm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerlin/excelchat-streamlit/8f40b050a4560575f2bfbc5b36ca062cf165e718/llm/__init__.py -------------------------------------------------------------------------------- /llm/ais_erniebot.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import List, Optional, Any, Mapping 3 | 4 | from langchain.callbacks.manager import CallbackManagerForLLMRun 5 | from langchain.callbacks.trubrics_callback import _convert_message_to_dict 6 | from langchain.chat_models.base import BaseChatModel 7 | from langchain.schema import BaseMessage, ChatResult, ChatGeneration, AIMessage 8 | 9 | import erniebot 10 | 11 | from pandasai.helpers import Logger 12 | from pydantic import BaseModel 13 | 14 | DEFAULT_MODEL_NAME = "ernie-bot" 15 | 16 | logger = Logger() 17 | 18 | 19 | class LLMTokenUsage(BaseModel): 20 | completion_tokens: int = 0 21 | prompt_tokens: int = 0 22 | total_tokens: int = 0 23 | 24 | 25 | class AIStudioErnieBot(BaseChatModel): 26 | """ 27 | Baidu AI Studio mode, support ernie-bot and ernie-bot-turbo. 28 | WARNING: aistudio mode is not compatible with multi tenants. 29 | """ 30 | model_name: str = DEFAULT_MODEL_NAME 31 | temperature: float = 0.1 32 | access_token: Optional[str] = None 33 | 34 | def __init__(self, access_token: str, **kwargs: Any) -> None: 35 | super().__init__(**kwargs) 36 | 37 | self.access_token = access_token 38 | logger.log(f"Baidu aistudio is used.", level=logging.INFO) 39 | erniebot.api_type = "aistudio" 40 | if erniebot.access_token is None or erniebot.access_token != access_token: 41 | erniebot.access_token = access_token 42 | self.model_name = kwargs.get("model_key", DEFAULT_MODEL_NAME) 43 | 44 | @property 45 | def _llm_type(self) -> str: 46 | return "baidu-as-ernie-bot" 47 | 48 | def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]] = None, 49 | run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) -> ChatResult: 50 | logger.log(f"Payload for ernie api is {messages}", level=logging.DEBUG) 51 | resp = erniebot.ChatCompletion.create( 52 | model=self.model_name, 53 | messages=[_convert_message_to_dict(m) for m in messages], 54 | temperature=self.temperature, 55 | top_p=0.95, 56 | stream=False, 57 | ) 58 | if resp.get("error_code"): 59 | raise ValueError(f"Error from BaiduAIStudioErnieBot api response: {resp}") 60 | 61 | return self._create_chat_result(resp) 62 | 63 | def _create_chat_result(self, response: Mapping[str, Any]) -> ChatResult: 64 | generations = [ 65 | ChatGeneration(message=AIMessage(content=response.get("result"))) 66 | ] 67 | token_usage = response.get("usage", {}) 68 | llm_output = {"token_usage": token_usage, "model_name": self.model_name} 69 | return ChatResult(generations=generations, llm_output=llm_output) 70 | 71 | def _combine_llm_outputs(self, llm_outputs: List[Optional[dict]]) -> dict: 72 | total_usage = LLMTokenUsage() 73 | for output in llm_outputs: 74 | if output is None: 75 | continue 76 | 77 | usage = output["token_usage"] 78 | total_usage.total_tokens += int(usage["total_tokens"]) 79 | total_usage.completion_tokens += int(usage["completion_tokens"]) 80 | total_usage.prompt_tokens += int(usage["prompt_tokens"]) 81 | 82 | return total_usage.dict() 83 | -------------------------------------------------------------------------------- /middleware/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerlin/excelchat-streamlit/8f40b050a4560575f2bfbc5b36ca062cf165e718/middleware/__init__.py -------------------------------------------------------------------------------- /middleware/base.py: -------------------------------------------------------------------------------- 1 | from pandasai.middlewares import ChartsMiddleware 2 | 3 | 4 | class CustomChartsMiddleware(ChartsMiddleware): 5 | def run(self, code: str) -> str: 6 | # code = super().run(code) 7 | 8 | processed = [] 9 | for line in code.split("\n"): 10 | if line.find("plt.close()") != -1: 11 | idx = line.find("plt") 12 | blank = "".join([' ' for c in range(idx)]) 13 | # Fix the chinese character display issue 14 | processed.append(blank + "plt.rcParams['font.sans-serif']=['SimHei']") 15 | processed.append(blank + "plt.rcParams['axes.unicode_minus']=False") 16 | # processed.append(blank + "plt.savefig('temp_chart.png')") 17 | processed.append(line) 18 | else: 19 | processed.append(line) 20 | code = "\n".join(processed) 21 | return code 22 | -------------------------------------------------------------------------------- /parser/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/developerlin/excelchat-streamlit/8f40b050a4560575f2bfbc5b36ca062cf165e718/parser/__init__.py -------------------------------------------------------------------------------- /parser/response_parser.py: -------------------------------------------------------------------------------- 1 | import shutil 2 | import tempfile 3 | import uuid 4 | from pathlib import Path 5 | from typing import Any 6 | 7 | from pandasai.responses import ResponseParser 8 | 9 | 10 | class CustomResponseParser(ResponseParser): 11 | def format_plot(self, result: dict) -> Any: 12 | super().format_plot(result) 13 | filename = str(uuid.uuid4()).replace("-", "") 14 | 15 | temp_image_path = Path(f"{tempfile.tempdir}/streamlit/{filename}.png") 16 | temp_image_path.parent.mkdir(parents=True, exist_ok=True) 17 | 18 | original_path = Path("temp_chart.png") 19 | shutil.copy(original_path, temp_image_path) 20 | print("image created: ", str(temp_image_path)) 21 | return {"type": "plot", "value": str(temp_image_path)} 22 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp==3.8.6 2 | aiosignal==1.3.1 3 | altair==5.1.2 4 | annotated-types==0.6.0 5 | anyio==3.7.1 6 | appnope==0.1.3 7 | astor==0.8.1 8 | asttokens==2.4.0 9 | async-timeout==4.0.3 10 | attrs==23.1.0 11 | backcall==0.2.0 12 | bce-python-sdk==0.8.92 13 | blinker==1.6.3 14 | cachetools==5.3.1 15 | certifi==2023.7.22 16 | charset-normalizer==3.3.0 17 | click==8.1.7 18 | colorlog==6.7.0 19 | contourpy==1.1.1 20 | cycler==0.12.1 21 | dataclasses-json==0.6.1 22 | decorator==5.1.1 23 | duckdb==0.8.1 24 | erniebot==0.3.1 25 | et-xmlfile==1.1.0 26 | exceptiongroup==1.1.3 27 | executing==2.0.0 28 | fonttools==4.43.1 29 | frozenlist==1.4.0 30 | future==0.18.3 31 | gitdb==4.0.10 32 | GitPython==3.1.40 33 | idna==3.4 34 | importlib-metadata==6.8.0 35 | importlib-resources==6.1.0 36 | ipython==8.16.1 37 | jedi==0.19.1 38 | Jinja2==3.1.2 39 | jsonpatch==1.33 40 | jsonpointer==2.4 41 | jsonschema==4.19.1 42 | jsonschema-specifications==2023.7.1 43 | kiwisolver==1.4.5 44 | langchain==0.0.319 45 | langsmith==0.0.47 46 | markdown-it-py==3.0.0 47 | MarkupSafe==2.1.3 48 | marshmallow==3.20.1 49 | matplotlib==3.8.0 50 | matplotlib-inline==0.1.6 51 | mdurl==0.1.2 52 | multidict==6.0.4 53 | mypy-extensions==1.0.0 54 | numpy==1.26.1 55 | openai==0.27.10 56 | openpyxl==3.1.2 57 | packaging==23.2 58 | pandas==1.5.3 59 | pandasai==1.3.3 60 | parso==0.8.3 61 | pexpect==4.8.0 62 | pickleshare==0.7.5 63 | Pillow==10.1.0 64 | prompt-toolkit==3.0.39 65 | protobuf==4.24.4 66 | ptyprocess==0.7.0 67 | pure-eval==0.2.2 68 | pyarrow==13.0.0 69 | pycryptodome==3.19.0 70 | pydantic==1.10.13 71 | pydantic_core==2.10.1 72 | pydeck==0.8.1b0 73 | Pygments==2.16.1 74 | pyparsing==3.1.1 75 | python-dateutil==2.8.2 76 | python-dotenv==1.0.0 77 | pytz==2023.3.post1 78 | PyYAML==6.0.1 79 | referencing==0.30.2 80 | requests==2.31.0 81 | rich==13.6.0 82 | rpds-py==0.10.6 83 | scipy==1.11.3 84 | six==1.16.0 85 | smmap==5.0.1 86 | sniffio==1.3.0 87 | SQLAlchemy==1.4.49 88 | stack-data==0.6.3 89 | streamlit==1.27.2 90 | tenacity==8.2.3 91 | toml==0.10.2 92 | toolz==0.12.0 93 | tornado==6.3.3 94 | tqdm==4.66.1 95 | traitlets==5.11.2 96 | typing-inspect==0.9.0 97 | typing_extensions==4.8.0 98 | tzdata==2023.3 99 | tzlocal==5.1 100 | urllib3==2.0.7 101 | validators==0.22.0 102 | wcwidth==0.2.8 103 | yarl==1.9.2 104 | zipp==3.17.0 105 | -------------------------------------------------------------------------------- /util.py: -------------------------------------------------------------------------------- 1 | from langchain.chat_models import ErnieBotChat 2 | from langchain.llms.ollama import Ollama 3 | from pandasai.llm import OpenAI, LangchainLLM 4 | from pandasai.prompts import GeneratePythonCodePrompt 5 | 6 | from llm.ais_erniebot import AIStudioErnieBot 7 | 8 | 9 | def get_open_ai_model(api_key): 10 | return OpenAI(api_token=api_key) 11 | 12 | 13 | def get_ollama_model(model_key, base_url): 14 | llm = Ollama(model=model_key, base_url=base_url, verbose=True) 15 | return LangchainLLM(langchain_llm=llm) 16 | 17 | 18 | def get_baidu_as_model(access_token): 19 | llm_core = AIStudioErnieBot(access_token=access_token, verbose=True) 20 | return LangchainLLM(llm_core) 21 | 22 | 23 | def get_baidu_qianfan_model(client_id, client_secret): 24 | llm_core = ErnieBotChat( 25 | model_name="ERNIE-Bot", 26 | temperature=0.1, 27 | ernie_client_id=client_id, 28 | ernie_client_secret=client_secret 29 | ) 30 | return LangchainLLM(llm_core) 31 | 32 | 33 | def get_prompt_template(): 34 | instruction_template = """ 35 | 使用提供的 dataframes ('dfs') 分析这个数据,过程中不要调用 dataframe set_index 对数据排序. 36 | 1. 准备: 如果有必要对数据做预处理和清洗 37 | 2. 执行: 对数据进行数据分析操作 (grouping, filtering, aggregating, etc.) 38 | 3. 分析: 进行实际分析(如果用户要求plot chart,请在代码中添加如下两行代码设置字体, 并将结果保存为图像文件temp_chart.png,并且不显示图表) 39 | plt.rcParams['font.sans-serif']=['SimHei'] 40 | plt.rcParams['axes.unicode_minus']=False 41 | """ 42 | custom_template = GeneratePythonCodePrompt(custom_instructions=instruction_template) 43 | return custom_template 44 | --------------------------------------------------------------------------------