-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchallenge-09.py
257 lines (213 loc) · 7.71 KB
/
challenge-09.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import json
import streamlit as st
from duckduckgo_search import DDGS
from openai import OpenAI, AssistantEventHandler
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
from typing_extensions import override
st.set_page_config(
page_title="::: Research Assistant :::",
page_icon="📜",
)
st.title("Research Assistant")
st.markdown(
"""
Use this chatbot to research something you're curious about.
1. Choose a favorite language (Korean, ...).
2. Choose an AI model (gpt-4o-mini, ...).
3. Input your OpenAI API Key on the sidebar.
4. Ask questions to research something you wonder.
"""
)
st.divider()
with st.sidebar:
# Select Favorite Language
language = st.selectbox(
"Choose your favorite language",
("Korean", "English", "Spanish", "Chinese", "Japanese"),
)
# Select AI Model
selected_model = st.selectbox(
"Choose your AI Model",
(
"gpt-4o-mini",
"gpt-3.5-turbo",
),
)
# Input LLM API Key
openai_api_key = st.text_input(
"Input your OpenAI API Key",
type="password",
)
# Link to Github Repo
st.markdown("---")
github_link = (
"https://github.com/toweringcloud/fullstack-gpt-v2/blob/main/challenge-09.py"
)
badge_link = "https://badgen.net/badge/icon/GitHub?icon=github&label"
st.write(f"[![Repo]({badge_link})]({github_link})")
# define function logic
def WikipediaSearchTool(params):
query = params["query"]
search = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
return search.invoke(query)
def DuckDuckGoSearchTool(params):
query = params["query"]
search = DDGS().text(query)
return json.dumps(list(search))
def SearchResultParseTool(params):
link = params["link"]
loader = WebBaseLoader(link, verify_ssl=True)
return loader.load()
# define function mapper
functions_map = {
"wiki_search": WikipediaSearchTool,
"ddg_search": DuckDuckGoSearchTool,
}
# define function schema
functions = [
{
"type": "function",
"function": {
"name": "wiki_search",
"description": "Search information on wikipedia site",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "user's input",
},
},
"required": ["query"],
},
},
},
{
"type": "function",
"function": {
"name": "ddg_search",
"description": "Search information on duckduckgo site",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "user's input",
},
},
"required": ["query"],
},
},
},
]
# https://platform.openai.com/docs/assistants/tools/function-calling?context=streaming
# assistant event handler with streaming
class EventHandler(AssistantEventHandler):
message = ""
@override
def on_event(self, event):
# Retrieve events that are denoted with 'requires_action'
# since these will have our tool_calls
if event.event == "thread.run.requires_action":
run_id = event.data.id
self.message_box = st.empty()
self.handle_requires_action(event.data, run_id)
def handle_requires_action(self, data, run_id):
tool_outputs = []
for tool in data.required_action.submit_tool_outputs.tool_calls:
print(
f"# tool: {tool.id} | {tool.function.name} | {tool.function.arguments}"
)
tool_outputs.append(
{
"tool_call_id": tool.id,
"output": functions_map[tool.function.name](
json.loads(tool.function.arguments)
),
}
)
# Submit all tool_outputs at the same time
self.submit_tool_outputs(tool_outputs, run_id)
def submit_tool_outputs(self, tool_outputs, run_id):
client = st.session_state["client"]
# Use the submit_tool_outputs_stream helper
with client.beta.threads.runs.submit_tool_outputs_stream(
thread_id=self.current_run.thread_id,
run_id=self.current_run.id,
tool_outputs=tool_outputs,
event_handler=EventHandler(),
) as stream:
for text in stream.text_deltas:
self.message += text
self.message_box.markdown(self.message)
print(text, end="", flush=True)
print()
self.save_research_result()
def save_research_result(self):
st.session_state["result"] = self.message
file_path = "./challenge-09.result"
with open(file_path, "w+", encoding="utf-8") as f:
f.write(self.message)
st.markdown(f"✨ research result saved at {file_path}")
st.download_button("::: Download :::", st.session_state["result"])
def main():
client = None
if "client" in st.session_state:
client = st.session_state["client"]
assistant = st.session_state["assistant"]
thread = st.session_state["thread"]
else:
if not openai_api_key:
st.error("Please input your OpenAI API Key on the sidebar.")
return
client = OpenAI(api_key=openai_api_key)
assistant = client.beta.assistants.create(
name="Research Expert",
instructions="""
You are a professional web research assistant.
Search information by query and summarize the result.
Please, all the chat messages should be written as {} language.
""".format(
language
),
temperature=0.1,
model=selected_model,
tools=functions,
)
thread = client.beta.threads.create()
st.session_state["client"] = client
st.session_state["assistant"] = assistant
st.session_state["thread"] = thread
with st.chat_message("ai"):
st.markdown("I'm ready! Ask away!")
# show messages in the thread of your assistant
messages = client.beta.threads.messages.list(thread_id=thread.id)
if messages:
messages = list(messages)
messages.reverse()
for message in messages:
st.chat_message(message.role).write(message.content[0].text.value)
# ready to research your question
question = st.chat_input("Ask anything you're curious about.")
if question:
with st.chat_message("human"):
st.markdown(question)
message = client.beta.threads.messages.create(
thread_id=thread.id, role="user", content=question
)
with st.chat_message("ai"):
st.markdown("Researching about `{}`".format(question))
with client.beta.threads.runs.stream(
thread_id=thread.id,
assistant_id=assistant.id,
event_handler=EventHandler(),
) as stream:
stream.until_done()
else:
st.empty()
try:
main()
except Exception as e:
st.write(e)