eagle0504 commited on
Commit
c07cbe4
Β·
verified Β·
1 Parent(s): da08cf9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -173
app.py CHANGED
@@ -1,207 +1,130 @@
 
 
1
  import streamlit as st
2
  import os
3
- import json
4
-
5
- from helper import ChatBot, intent_processor, load_metadata, resolve_and_execute
6
- import list_of_apis # Ensures that API functions are registered
7
- from main import AgentX
8
-
9
- # Initialize session state for messages if not already done
10
- if "messages" not in st.session_state:
11
- st.session_state.messages = [{"role": "system", "content": "You are a helpful agent."}]
12
-
13
- # Load metadata
14
- metadata_filepath = os.path.join(os.path.dirname(__file__), "metadata.json")
15
- metadata = load_metadata(metadata_filepath)
16
-
17
- # Define API keys and tokens (replace with actual credentials or environment variables)
18
- API_KEY = os.environ["OPENAI_API_KEY"]
19
- ACCOUNT_SID = os.environ["TWILIO_ACCOUNT_SID"]
20
- AUTH_TOKEN = os.environ["TWILIO_AUTH_TOKEN"]
21
- SERPAPI_KEY = os.environ["SERPAPI_KEY"]
22
-
23
- # Initialize the AgentX
24
- agent = AgentX(
25
- api_key=API_KEY,
26
- account_sid=ACCOUNT_SID,
27
- auth_token=AUTH_TOKEN,
28
- serpapi_key=SERPAPI_KEY,
29
- )
30
-
31
- # Streamlit UI
32
- st.title("AgentX Chatbot")
33
- st.sidebar.write("### Examples")
34
- st.sidebar.write("1. Send a message to someone via SMS")
35
- st.sidebar.write("2. Search on Google")
36
- st.sidebar.write("Type your question below and press Enter.")
37
-
38
- # React to user input
39
- if prompt := st.chat_input("πŸ˜‰ Ask any question or feel free to use the examples provided in the left sidebar."):
40
-
41
- # Display user message in chat message container
42
- st.chat_message("user").markdown(prompt)
43
-
44
- # Add user message to chat history
45
- st.session_state.messages.append({"role": "user", "content": prompt})
46
-
47
- # Add user message to event stream in AgentX
48
- agent.event_stream.append({"event": "user_message", "content": prompt})
49
-
50
- # Process intent and detect any API calls
51
- intent_processor(agent.event_stream, metadata, agent.bot)
52
 
53
- # Define secrets for API calls
54
- secrets = {
55
- "account_sid": agent.account_sid,
56
- "auth_token": agent.auth_token,
57
- "serpapi_key": agent.serpapi_key,
58
- }
59
 
60
- # Resolve and execute any API calls if detected
61
- resolve_and_execute(agent.event_stream, metadata, secrets)
62
-
63
- # Get the bot's response based on conversation history
64
- response = agent.bot.generate_response(prompt)
65
-
66
- # Display assistant response in chat message container
67
- with st.chat_message("assistant"):
68
- st.markdown(response)
69
-
70
- # Add assistant response to chat history
71
- st.session_state.messages.append({"role": "assistant", "content": response})
72
 
73
-
74
-
75
- # from datetime import datetime
76
-
77
- # import streamlit as st
78
- # import os
79
- # from openai import OpenAI
80
-
81
-
82
- # class ChatBot:
83
- # def __init__(self):
84
- # self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
85
- # self.history = [{"role": "system", "content": "You are a helpful assistant."}]
86
-
87
- # def generate_response(self, prompt: str) -> str:
88
- # self.history.append({"role": "user", "content": prompt})
89
 
90
- # completion = self.client.chat.completions.create(
91
- # model="gpt-3.5-turbo", # NOTE: feel free to change it to "gpt-4" or "our LLM"
92
- # messages=self.history
93
- # )
94
 
95
- # response = completion.choices[0].message.content
96
- # self.history.append({"role": "assistant", "content": response})
97
 
98
- # return response
99
 
100
- # def get_history(self) -> list:
101
- # return self.history
102
 
103
 
104
- # # Read the content of the Markdown file
105
- # def read_markdown_file(file_path):
106
- # with open(file_path, 'r', encoding='utf-8') as file:
107
- # return file.read()
108
 
109
 
110
- # # Credit: Time
111
- # def current_year():
112
- # now = datetime.now()
113
- # return now.year
114
 
115
 
116
- # st.set_page_config(layout="wide")
117
- # st.title("Yin's Profile πŸ€–")
118
 
119
 
120
- # with st.sidebar:
121
- # with st.expander("Instruction Manual"):
122
- # st.markdown("""
123
- # ## Yin's Profile πŸ€– Chatbot
124
- # This Streamlit app allows you to chat with our LLM model.
125
 
126
- # ### How to Use:
127
- # 1. **Input**: Type your prompt into the chat input box labeled "What is up?".
128
- # 2. **Response**: The app will display a response from our LLM.
129
- # 3. **Chat History**: Previous conversations will be shown on the app.
130
 
131
- # ### Credits:
132
- # - **Developer**: [Yiqiao Yin](https://www.y-yin.io/) | [App URL](https://huggingface.co/spaces/eagle0504/y-yin-homepage) | [LinkedIn](https://www.linkedin.com/in/yiqiaoyin/) | [YouTube](https://youtube.com/YiqiaoYin/)
133
- # Enjoy chatting with Yin's assistant, Ava!
134
- # """)
135
 
136
- # # Example:
137
- # with st.expander("Examples"):
138
- # st.success("Example: Who is Yiqiao Yin?")
139
- # st.success("Example: What did Yiqiao do at graduate school?")
140
- # st.success("Example: Where to find published papers by Yiqiao?")
141
- # st.success("Example: What is Yiqiao's view on AI?")
142
- # st.success("Example: What are some online links by Yiqiao I can read about?")
143
- # st.success("Example: What is Yiqiao's view on stock market?")
144
 
145
- # # Add a button to clear the session state
146
- # if st.button("Clear Session"):
147
- # st.session_state.messages = []
148
- # st.experimental_rerun()
149
 
150
- # # Credit:
151
- # current_year = current_year() # This will print the current year
152
- # st.markdown(
153
- # f"""
154
- # <h6 style='text-align: left;'>Copyright Β© 2010-{current_year} Present Yiqiao Yin</h6>
155
- # """,
156
- # unsafe_allow_html=True,
157
- # )
158
 
159
- # # Initialize chat history
160
- # if "messages" not in st.session_state:
161
- # st.session_state.messages = []
162
-
163
- # # Ensure messages are a list of dictionaries
164
- # if not isinstance(st.session_state.messages, list):
165
- # st.session_state.messages = []
166
- # if not all(isinstance(msg, dict) for msg in st.session_state.messages):
167
- # st.session_state.messages = []
168
-
169
- # # Path to the Markdown file
170
- # md_file_path = 'docs/yiqiao_yin.md'
171
-
172
- # # Get the content of the Markdown file
173
- # yiqiaoyin_profile = read_markdown_file(md_file_path)
174
 
175
- # # Add the system message with the profile information to the chat history if it hasn't been added yet
176
- # if not any(msg["role"] == "system" for msg in st.session_state.messages):
177
- # st.session_state.messages.append({"role": "system", "content": f"You know the following about Mr. Yiqiao Yin: {yiqiaoyin_profile}"})
 
 
178
 
179
- # # Display chat messages from history on app rerun
180
- # for message in st.session_state.messages:
181
- # if message["role"] != "system": # Skip system messages
182
- # with st.chat_message(message["role"]):
183
- # st.markdown(message["content"])
184
 
185
- # # React to user input
186
- # if prompt := st.chat_input("πŸ˜‰ Ask any question or feel free to use the examples provided in the left sidebar."):
187
 
188
- # # Display user message in chat message container
189
- # st.chat_message("user").markdown(prompt)
 
190
 
191
- # # Add user message to chat history
192
- # st.session_state.messages.append({"role": "user", "content": prompt})
 
 
 
193
 
194
- # # API Call
195
- # bot = ChatBot()
196
- # bot.history = st.session_state.messages.copy() # Update history from messages
197
- # response = bot.generate_response(prompt)
198
 
199
- # # Display assistant response in chat message container
200
- # with st.chat_message("assistant"):
201
- # st.markdown(response)
202
 
203
- # # Add assistant response to chat history
204
- # st.session_state.messages.append({"role": "assistant", "content": response})
205
 
 
 
 
 
206
 
 
 
 
207
 
 
 
 
1
+ from datetime import datetime
2
+
3
  import streamlit as st
4
  import os
5
+ from openai import OpenAI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
 
 
 
 
 
 
7
 
8
+ class ChatBot:
9
+ def __init__(self):
10
+ self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
11
+ self.history = [{"role": "system", "content": "You are a helpful assistant."}]
 
 
 
 
 
 
 
 
12
 
13
+ def generate_response(self, prompt: str) -> str:
14
+ self.history.append({"role": "user", "content": prompt})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ completion = self.client.chat.completions.create(
17
+ model="gpt-3.5-turbo", # NOTE: feel free to change it to "gpt-4" or "our LLM"
18
+ messages=self.history
19
+ )
20
 
21
+ response = completion.choices[0].message.content
22
+ self.history.append({"role": "assistant", "content": response})
23
 
24
+ return response
25
 
26
+ def get_history(self) -> list:
27
+ return self.history
28
 
29
 
30
+ # Read the content of the Markdown file
31
+ def read_markdown_file(file_path):
32
+ with open(file_path, 'r', encoding='utf-8') as file:
33
+ return file.read()
34
 
35
 
36
+ # Credit: Time
37
+ def current_year():
38
+ now = datetime.now()
39
+ return now.year
40
 
41
 
42
+ st.set_page_config(layout="wide")
43
+ st.title("Yin's Profile πŸ€–")
44
 
45
 
46
+ with st.sidebar:
47
+ with st.expander("Instruction Manual"):
48
+ st.markdown("""
49
+ ## Yin's Profile πŸ€– Chatbot
50
+ This Streamlit app allows you to chat with our LLM model.
51
 
52
+ ### How to Use:
53
+ 1. **Input**: Type your prompt into the chat input box labeled "What is up?".
54
+ 2. **Response**: The app will display a response from our LLM.
55
+ 3. **Chat History**: Previous conversations will be shown on the app.
56
 
57
+ ### Credits:
58
+ - **Developer**: [Yiqiao Yin](https://www.y-yin.io/) | [App URL](https://huggingface.co/spaces/eagle0504/y-yin-homepage) | [LinkedIn](https://www.linkedin.com/in/yiqiaoyin/) | [YouTube](https://youtube.com/YiqiaoYin/)
59
+ Enjoy chatting with Yin's assistant, Ava!
60
+ """)
61
 
62
+ # Example:
63
+ with st.expander("Examples"):
64
+ st.success("Example: Who is Yiqiao Yin?")
65
+ st.success("Example: What did Yiqiao do at graduate school?")
66
+ st.success("Example: Where to find published papers by Yiqiao?")
67
+ st.success("Example: What is Yiqiao's view on AI?")
68
+ st.success("Example: What are some online links by Yiqiao I can read about?")
69
+ st.success("Example: What is Yiqiao's view on stock market?")
70
 
71
+ # Add a button to clear the session state
72
+ if st.button("Clear Session"):
73
+ st.session_state.messages = []
74
+ st.experimental_rerun()
75
 
76
+ # Credit:
77
+ current_year = current_year() # This will print the current year
78
+ st.markdown(
79
+ f"""
80
+ <h6 style='text-align: left;'>Copyright Β© 2010-{current_year} Present Yiqiao Yin</h6>
81
+ """,
82
+ unsafe_allow_html=True,
83
+ )
84
 
85
+ # Initialize chat history
86
+ if "messages" not in st.session_state:
87
+ st.session_state.messages = []
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
+ # Ensure messages are a list of dictionaries
90
+ if not isinstance(st.session_state.messages, list):
91
+ st.session_state.messages = []
92
+ if not all(isinstance(msg, dict) for msg in st.session_state.messages):
93
+ st.session_state.messages = []
94
 
95
+ # Path to the Markdown file
96
+ md_file_path = 'docs/yiqiao_yin.md'
 
 
 
97
 
98
+ # Get the content of the Markdown file
99
+ yiqiaoyin_profile = read_markdown_file(md_file_path)
100
 
101
+ # Add the system message with the profile information to the chat history if it hasn't been added yet
102
+ if not any(msg["role"] == "system" for msg in st.session_state.messages):
103
+ st.session_state.messages.append({"role": "system", "content": f"You know the following about Mr. Yiqiao Yin: {yiqiaoyin_profile}"})
104
 
105
+ # Display chat messages from history on app rerun
106
+ for message in st.session_state.messages:
107
+ if message["role"] != "system": # Skip system messages
108
+ with st.chat_message(message["role"]):
109
+ st.markdown(message["content"])
110
 
111
+ # React to user input
112
+ if prompt := st.chat_input("πŸ˜‰ Ask any question or feel free to use the examples provided in the left sidebar."):
 
 
113
 
114
+ # Display user message in chat message container
115
+ st.chat_message("user").markdown(prompt)
 
116
 
117
+ # Add user message to chat history
118
+ st.session_state.messages.append({"role": "user", "content": prompt})
119
 
120
+ # API Call
121
+ bot = ChatBot()
122
+ bot.history = st.session_state.messages.copy() # Update history from messages
123
+ response = bot.generate_response(prompt)
124
 
125
+ # Display assistant response in chat message container
126
+ with st.chat_message("assistant"):
127
+ st.markdown(response)
128
 
129
+ # Add assistant response to chat history
130
+ st.session_state.messages.append({"role": "assistant", "content": response})