xuyingliKepler commited on
Commit
c5e1c8b
·
verified ·
1 Parent(s): bc9268a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +496 -0
app.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import faiss
4
+ from openai import OpenAI
5
+ import tempfile
6
+ from PyPDF2 import PdfReader
7
+ import io
8
+ from sentence_transformers import SentenceTransformer
9
+ import streamlit as st
10
+ from nltk.tokenize import word_tokenize
11
+ from nltk.corpus import stopwords
12
+ from nltk.stem import WordNetLemmatizer
13
+ from collections import Counter
14
+ #from langdetect import detect
15
+ #import jieba
16
+ #import jieba.analyse
17
+ import nltk
18
+ import os
19
+
20
+ os.environ["OPENAI_API_KEY"]= st.secrets["OPENAI_API_KEY"]
21
+ api_key = os.environ["OPENAI_API_KEY"]
22
+
23
+ @st.cache_data
24
+ def download_nltk():
25
+ nltk.download('punkt')
26
+ nltk.download('wordnet')
27
+ nltk.download('stopwords')
28
+
29
+ def chunkstring(string, length):
30
+ return (string[0+i:length+i] for i in range(0, len(string), length))
31
+
32
+ def pdf_parser(input_pdf):
33
+ pdf = PdfReader(input_pdf)
34
+ pdf_content = ""
35
+ for page in pdf.pages:
36
+ pdf_content += page.extract_text()
37
+ return pdf_content
38
+
39
+ def get_keywords(file_paths): #这里的重点是,对每一个file做尽可能简短且覆盖全面的summarization
40
+ download_nltk()
41
+ keywords_list = []
42
+ for file_path in file_paths:
43
+ with open(file_path, 'r') as file:
44
+ data = file.read()
45
+ # tokenize
46
+ words = word_tokenize(data)
47
+ # remove punctuation
48
+ words = [word for word in words if word.isalnum()]
49
+ # remove stopwords
50
+ stop_words = set(stopwords.words('english'))
51
+ words = [word for word in words if word not in stop_words]
52
+ # lemmatization
53
+ lemmatizer = WordNetLemmatizer()
54
+ words = [lemmatizer.lemmatize(word) for word in words]
55
+ # count word frequencies
56
+ word_freq = Counter(words)
57
+ # get top 20 most common words
58
+ keywords = word_freq.most_common(20)
59
+ new_keywords = []
60
+ for word in keywords:
61
+ new_keywords.append(word[0])
62
+ str_keywords = ''
63
+ for word in new_keywords:
64
+ str_keywords += word + ", "
65
+ keywords_list.append(f"Top20 frequency keywords for {file_path}: {str_keywords}")
66
+
67
+ return keywords_list
68
+
69
+
70
+ def get_completion_from_messages(client, messages, model="gpt-4o-mini", temperature=0):
71
+ client = client
72
+ completion = client.chat.completions.create(
73
+ model=model,
74
+ messages=messages,
75
+ temperature=temperature,
76
+ )
77
+ return completion.choices[0].message.content
78
+
79
+ def genarating_outline(client, keywords, num_lessons,language):
80
+ system_message = 'You are a great AI teacher and linguist, skilled at create course outline based on summarized knowledge materials.'
81
+ user_message = f"""You are a great AI teacher and linguist,
82
+ skilled at generating course outline based on keywords of the course.
83
+ Based on keywords provided, you should carefully design a course outline.
84
+ Requirements: Through learning this course, learner should understand those key concepts.
85
+ Key concepts: {keywords}
86
+ you should output course outline in a python list format, Do not include anything else except that python list in your output.
87
+ Example output format:
88
+ [[name_lesson1, abstract_lesson1],[name_lesson2, abstrct_lesson2]]
89
+ In the example, you can see each element in this list consists of two parts: the "name_lesson" part is the name of the lesson, and the "abstract_lesson" part is the one-sentence description of the lesson, intruduces knowledge it contained.
90
+ for each lesson in this course, you should provide these two information and organize them as exemplified.
91
+ for this course, you should design {num_lessons} lessons in total.
92
+ the course outline should be written in {language}.
93
+ Start the work now.
94
+ """
95
+ messages = [
96
+ {'role':'system',
97
+ 'content': system_message},
98
+ {'role':'user',
99
+ 'content': user_message},
100
+ ]
101
+
102
+ response = get_completion_from_messages(client, messages)
103
+
104
+ list_response = ['nothing in the answers..']
105
+
106
+ try:
107
+ list_response = eval(response)
108
+ except SyntaxError:
109
+ pass
110
+
111
+ return list_response
112
+
113
+ def courseOutlineGenerating(client, file_paths, num_lessons, language):
114
+ summarized_materials = get_keywords(file_paths)
115
+ course_outline = genarating_outline(client, summarized_materials, num_lessons, language)
116
+ return course_outline
117
+
118
+ def constructVDB(file_paths):
119
+ #把KM拆解为chunks
120
+
121
+ chunks = []
122
+ for filename in file_paths:
123
+ with open(filename, 'r') as f:
124
+ content = f.read()
125
+ for chunk in chunkstring(content, 730):
126
+ chunks.append(chunk)
127
+ chunk_df = pd.DataFrame(chunks, columns=['chunk'])
128
+
129
+ #从文本chunks到embeddings
130
+ model = SentenceTransformer('paraphrase-mpnet-base-v2', device='cuda')
131
+ embeddings = model.encode(chunk_df['chunk'].tolist())
132
+ # convert embeddings to a dataframe
133
+ embedding_df = pd.DataFrame(embeddings.tolist())
134
+ # Concatenate the original dataframe with the embeddings
135
+ paraphrase_embeddings_df = pd.concat([chunk_df, embedding_df], axis=1)
136
+ # Save the results to a new csv file
137
+
138
+ #从embeddings到向量数据库
139
+ # Load the embeddings
140
+ embeddings = paraphrase_embeddings_df.iloc[:, 1:].values # All columns except the first (chunk text)
141
+ # Ensure that the array is C-contiguous
142
+ embeddings = np.ascontiguousarray(embeddings, dtype=np.float32)
143
+ # Preparation for Faiss
144
+ dimension = embeddings.shape[1] # the dimension of the vector space
145
+ index = faiss.IndexFlatL2(dimension)
146
+ # Normalize the vectors
147
+ faiss.normalize_L2(embeddings)
148
+ # Build the index
149
+ index.add(embeddings)
150
+ # write index to disk
151
+ return paraphrase_embeddings_df, index
152
+
153
+ def searchVDB(search_sentence, paraphrase_embeddings_df, index):
154
+ #从向量数据库中检索相应文段
155
+ try:
156
+ data = paraphrase_embeddings_df
157
+ embeddings = data.iloc[:, 1:].values # All columns except the first (chunk text)
158
+ embeddings = np.ascontiguousarray(embeddings, dtype=np.float32)
159
+
160
+ model = SentenceTransformer('paraphrase-mpnet-base-v2')
161
+ sentence_embedding = model.encode([search_sentence])
162
+
163
+ # Ensuring the sentence embedding is in the correct format
164
+ sentence_embedding = np.ascontiguousarray(sentence_embedding, dtype=np.float32)
165
+ # Searching for the top 3 nearest neighbors in the FAISS index
166
+ D, I = index.search(sentence_embedding, k=3)
167
+ # Printing the top 3 most similar text chunks
168
+ retrieved_chunks_list = []
169
+ for idx in I[0]:
170
+ retrieved_chunks_list.append(data.iloc[idx].chunk)
171
+
172
+ except Exception:
173
+ retrieved_chunks_list = []
174
+
175
+ return retrieved_chunks_list
176
+
177
+ def generateCourse(client, topic, materials, language, style_options):
178
+ system_message = 'You are a great AI teacher and linguist, skilled at writing informative and easy-to-understand course script based on given lesson topic and knowledge materials.'
179
+
180
+ user_message = f"""You are a great AI teacher and linguist,
181
+ skilled at writing informative and easy-to-understand course script based on given lesson topic and knowledge materials.\n
182
+ You should write a course for new hands, they need detailed and vivid explaination to understand the topic. \n
183
+ A high-quality course should meet requirements below:\n
184
+ (1) Contains enough facts, data and figures to be convincing\n
185
+ (2) The internal narrative is layered and logical, not a simple pile of items\n
186
+ Make sure all these requirements are considered when writing the lesson script content.\n
187
+ Please follow this procedure step-by-step when disgning the course:\n
188
+ Step 1. Write down the teaching purpose of the lesson initially in the script. \n
189
+ Step 2. Write down the outline of this lesson (outline is aligned to the teaching purpose), then follow the outline to write the content. Make sure every concept in the outline is explined adequately in the course. \n
190
+ Your lesson topic and abstract is within the 「」 quotes, and the knowledge materials are within the 【】 brackets. \n
191
+ lesson topic and abstract: 「{topic}」, \n
192
+ knowledge materials related to this lesson:【{materials} 】 \n
193
+ the script should be witten in {language}, and mathematical symbols should be written in markdown form. \n
194
+ {style_options} \n
195
+ Start writting the script of this lesson now.
196
+ """
197
+
198
+ messages = [
199
+ {'role':'system',
200
+ 'content': system_message},
201
+ {'role':'user',
202
+ 'content': user_message},
203
+ ]
204
+
205
+ response = get_completion_from_messages(client, messages)
206
+ return response
207
+
208
+ def decorate_user_question(user_question, retrieved_chunks_for_user):
209
+ decorated_prompt = f'''You're a brilliant teaching assistant, skilled at answer stundent's question based on given materials.
210
+ student's question: 「{user_question}」
211
+ related materials:【{retrieved_chunks_for_user}】
212
+ if the given materials are irrelavant to student's question, please use your own knowledge to answer the question.
213
+ You need to break down the student's question first, find out what he really wants to ask, and then try your best to give a comprehensive answer.
214
+ The language you're answering in should aligned with what student is using.
215
+ Now you're talking to the student. Please answer.
216
+ '''
217
+ return decorated_prompt
218
+
219
+ def initialize_file(added_files):
220
+ temp_file_paths = []
221
+ with st.spinner('Processing file...'):
222
+ for added_file in added_files:
223
+ if added_file.name.endswith(".pdf"):
224
+ string = pdf_parser(added_file)
225
+ with tempfile.NamedTemporaryFile(suffix=".md", delete=False) as tmp:
226
+ tmp.write(string.encode("utf-8"))
227
+ tmp_path = tmp.name
228
+ else:
229
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".md") as tmp:
230
+ tmp.write(added_file.getvalue())
231
+ tmp_path = tmp.name
232
+ temp_file_paths.append(tmp_path)
233
+ st.success('Processing file...Done')
234
+ return temp_file_paths
235
+
236
+ def initialize_vdb(temp_file_paths):
237
+ with st.spinner('Constructing vector database from provided materials...'):
238
+ embeddings_df, faiss_index = constructVDB(temp_file_paths)
239
+ st.success("Constructing vector database from provided materials...Done")
240
+ return embeddings_df, faiss_index
241
+
242
+ def initialize_outline(client, temp_file_paths, num_lessons, language):
243
+ with st.spinner('Generating Course Outline...'):
244
+ course_outline_list = courseOutlineGenerating(client, temp_file_paths, num_lessons, language)
245
+ st.success("Generating Course Outline...Done")
246
+ course_outline_string = ''
247
+ lessons_count = 0
248
+ for outline in course_outline_list:
249
+ lessons_count += 1
250
+ course_outline_string += f"{lessons_count}." + outline[0]
251
+ course_outline_string += '\n\n' + outline[1] + '\n\n'
252
+ with st.expander("Check the course outline", expanded=False):
253
+ st.write(course_outline_string)
254
+
255
+ return course_outline_list
256
+
257
+ def initialize_content(client, course_outline_list, embeddings_df, faiss_index, language, style_options):
258
+ count_generating_content = 0
259
+ course_content_list = []
260
+ for lesson in course_outline_list:
261
+ count_generating_content += 1
262
+ with st.spinner(f"Writing content for lesson {count_generating_content}..."):
263
+ retrievedChunksList = searchVDB(lesson, embeddings_df, faiss_index)
264
+ courseContent = generateCourse(client, lesson, retrievedChunksList, language, style_options)
265
+ course_content_list.append(courseContent)
266
+ st.success(f"Writing content for lesson {count_generating_content}...Done")
267
+ with st.expander(f"Learn the lesson {count_generating_content} ", expanded=False):
268
+ st.markdown(courseContent)
269
+ return course_content_list
270
+
271
+ def regenerate_outline(course_outline_list):
272
+ try:
273
+ course_outline_string = ''
274
+ lessons_count = 0
275
+ for outline in course_outline_list:
276
+ lessons_count += 1
277
+ course_outline_string += f"{lessons_count}." + outline[0]
278
+ course_outline_string += '\n\n' + outline[1] + '\n\n'
279
+ with st.expander("Check the course outline", expanded=False):
280
+ st.write(course_outline_string)
281
+ except Exception:
282
+ pass
283
+
284
+ def regenerate_content(course_content_list):
285
+ try:
286
+ count_generating_content = 0
287
+ for content in course_content_list:
288
+ count_generating_content += 1
289
+ with st.expander(f"Learn the lesson {count_generating_content} ", expanded=False):
290
+ st.markdown(content)
291
+ except Exception:
292
+ pass
293
+
294
+ def add_prompt_course_style(selected_style_list):
295
+ initiate_prompt = 'Please be siginificantly aware that this course is requested to: \n'
296
+ customize_prompt = ''
297
+ if len(selected_style_list) != 0:
298
+ customize_prompt += initiate_prompt
299
+ for style in selected_style_list:
300
+ if style == "More examples":
301
+ customize_prompt += '- **contain more examples**. You should use your own knowledge to vividly exemplify key concepts occured in this course.\n'
302
+ elif style == "More excercises":
303
+ customize_prompt += '- **contain more excercises**. So last part of this lesson should be excercises.\n'
304
+ elif style == "Easier to learn":
305
+ customize_prompt += '- **Be easier to learn**. So you should use plain language to write the lesson script, and apply some metaphors & analogys wherever appropriate.\n'
306
+ return customize_prompt
307
+
308
+ def app():
309
+ st.title("AI Learning assistant v0.1.0")
310
+ divider = st.divider()
311
+ st.markdown("""
312
+ <style>
313
+ .footer {
314
+ position: fixed;
315
+ bottom: 0;
316
+ right: 10px;
317
+ width: auto;
318
+ background-color: transparent;
319
+ text-align: right;
320
+ padding-right: 10px;
321
+ padding-bottom: 10px;
322
+ }
323
+ </style>
324
+ """, unsafe_allow_html=True)
325
+ with st.sidebar:
326
+ api_key = ''
327
+ st.image("simpsons.png")
328
+ added_files = st.file_uploader('Upload .md or .pdf files, simultaneous mixed upload these types is supported.', type=['.md','.pdf'], accept_multiple_files=True)
329
+ with st.expander('Customize my course'):
330
+ num_lessons = st.slider('How many lessons do you want this course to have?', min_value=2, max_value=15, value=5, step=1)
331
+ custom_options = st.multiselect(
332
+ 'Preferred teaching style :grey[(Recommend new users not to select)]',
333
+ ['More examples', 'More excercises', 'Easier to learn'],
334
+ max_selections = 2
335
+ )
336
+ style_options = add_prompt_course_style(custom_options)
337
+ language = 'English'
338
+ Chinese = st.checkbox('Output in Chinese')
339
+ if Chinese:
340
+ language = 'Chinese'
341
+
342
+ btn = st.button('Generate my course!')
343
+
344
+ if "description1" not in st.session_state:
345
+ st.session_state.description = ''
346
+ if "start_col1" not in st.session_state:
347
+ st.session_state.start_col1 = st.empty()
348
+ if "start_col2" not in st.session_state:
349
+ st.session_state.start_col2 = st.empty()
350
+ if "case_pay" not in st.session_state:
351
+ st.session_state.case_pay = st.empty()
352
+
353
+ if "embeddings_df" not in st.session_state:
354
+ st.session_state.embeddings_df = ''
355
+ if "faiss_index" not in st.session_state:
356
+ st.session_state.faiss_index = ''
357
+ if "course_outline_list" not in st.session_state:
358
+ st.session_state.course_outline_list = ''
359
+ if "course_content_list" not in st.session_state:
360
+ st.session_state.course_content_list = ''
361
+
362
+ if "OPENAI_API_KEY" not in st.session_state:
363
+ st.session_state["OPENAI_API_KEY"] = ''
364
+ #if "client" not in st.session_state:
365
+ # st.session_state["client"] = ''
366
+ if "openai_model" not in st.session_state:
367
+ st.session_state["openai_model"] = "gpt-4-1106-preview"
368
+ if "messages_ui" not in st.session_state:
369
+ st.session_state.messages_ui = []
370
+ if "messages" not in st.session_state:
371
+ st.session_state.messages = []
372
+
373
+ st.session_state.start_col1, st.session_state.start_col2 = st.columns(2)
374
+
375
+ with st.session_state.start_col1:
376
+ st.session_state.description = st.markdown('''
377
+ <font color = 'grey'> An all-round teacher. A teaching assistant who really knows the subject. **Anything. Anywhere. All at once.** </font> :100:
378
+
379
+ Github Repo: https://github.com/Siyuan-Harry/OmniTutor
380
+
381
+ ### ✨ Key features
382
+
383
+ - 🧑‍🏫 **Concise and clear course creation**: <font color = 'grey'>Generated from your learning notes (**.md**) or any learning materials (**.pdf**)!</font>
384
+ - 📚 **All disciplines**: <font color = 'grey'>Whether it's math, physics, literature, history or coding, OmniTutor covers it all.</font>
385
+ - ⚙️ **Customize your own course**: <font color = 'grey'>Choose your preferred teaching style, lesson count and language.</font>
386
+ - ⚡️ **Fast respond with trustable accuracy**: <font color = 'grey'>Problem-solving chat with the AI teaching assistant who really understand the materials.</font>
387
+
388
+ ### 🏃‍♂️ Get started!
389
+
390
+ 1. **Upload learning materials**: <font color = 'grey'>The upload widget in the sidebar supports PDF and .md files simutaenously.</font>
391
+ 2. **Customize your course**: <font color = 'grey'>By few clicks and swipes, adjusting teaching style, lesson count and language for your course.</font>
392
+ 3. **Start course generating**: <font color = 'grey'>Touch "Generate my course!" button in the sidebar, then watch how OmniTutor creates personal-customized course for you.</font>
393
+ 4. **Interactive learning**: <font color = 'grey'>Learn the course, and ask OmniTutor any questions related to this course whenever you encountered them.</font>
394
+
395
+ 🎉 Have fun Learning!
396
+
397
+ ''', unsafe_allow_html=True
398
+ )
399
+
400
+ if btn:
401
+ # api_key = os.environ["OPENAI_API_KEY"]
402
+ if api_key != "sk-..." and api_key !="" and api_key.startswith("sk-"):
403
+ st.session_state.start_col1.empty()
404
+ st.session_state.start_col2.empty()
405
+ st.session_state.description.empty()
406
+ st.session_state.case_pay.empty()
407
+ divider.empty()
408
+
409
+ #initialize app
410
+ temp_file_paths = initialize_file(added_files)
411
+ st.session_state["OPENAI_API_KEY"] = api_key
412
+ client = OpenAI(api_key = st.session_state["OPENAI_API_KEY"])
413
+ st.session_state.embeddings_df, st.session_state.faiss_index = initialize_vdb(temp_file_paths)
414
+ st.session_state.course_outline_list = initialize_outline(client, temp_file_paths, num_lessons, language)
415
+ st.session_state.course_content_list = initialize_content(client, st.session_state.course_outline_list, st.session_state.embeddings_df, st.session_state.faiss_index, language, style_options)
416
+
417
+ st.markdown('''
418
+ > 🤔 <font color = 'grey'> **Not satisfied with this course?** Simply click "Generate my course!" button to regenerate a new one! </font>
419
+ >
420
+ > 😁 <font color = 'grey'> If the course is good enough for you, learn and enter questions related in the input box below 👇... </font>
421
+
422
+ :blue[Wish you all the best in your learning journey :)]
423
+ ''', unsafe_allow_html=True)
424
+ else:
425
+ st.session_state.start_col1.empty()
426
+ st.session_state.start_col2.empty()
427
+ st.session_state.description.empty()
428
+ st.session_state.case_pay.empty()
429
+ divider.empty()
430
+
431
+
432
+ col1, col2 = st.columns([0.6,0.4])
433
+ user_question = st.chat_input("Enter your questions when learning...")
434
+
435
+ if user_question:
436
+ st.session_state.start_col1.empty()
437
+ st.session_state.start_col2.empty()
438
+ st.session_state.description.empty()
439
+ st.session_state.case_pay.empty()
440
+ divider.empty()
441
+
442
+ with col1:
443
+ #把课程大纲打印出来
444
+ regenerate_outline(st.session_state.course_outline_list)
445
+ #把课程内容打印出来
446
+ regenerate_content(st.session_state.course_content_list)
447
+
448
+ with col2:
449
+ st.caption(''':blue[AI Assistant]: Ask this TA any questions related to this course and get direct answers. :sunglasses:''')
450
+ # Set a default model
451
+
452
+ with st.chat_message("assistant"):
453
+ st.write("Hello👋, how can I help you today? 😄")
454
+
455
+ # Display chat messages from history on app rerun
456
+ for message in st.session_state.messages_ui:
457
+ with st.chat_message(message["role"]):
458
+ st.markdown(message["content"])
459
+
460
+ #更新ui上显示的聊天记录
461
+ st.session_state.messages_ui.append({"role": "user", "content": user_question})
462
+ # Display new user question.
463
+ with st.chat_message("user"):
464
+ st.markdown(user_question)
465
+
466
+ #这里的session.state就是保存了这个对话会话的一些基本信息和设置
467
+ retrieved_chunks_for_user = searchVDB(user_question, st.session_state.embeddings_df, st.session_state.faiss_index)
468
+ prompt = decorate_user_question(user_question, retrieved_chunks_for_user)
469
+ st.session_state.messages.append({"role": "user", "content": prompt})
470
+
471
+ # Display assistant response in chat message container
472
+ with st.chat_message("assistant"):
473
+ message_placeholder = st.empty()
474
+ full_response = ""
475
+ client = OpenAI(api_key = st.session_state["OPENAI_API_KEY"])
476
+ for response in client.chat.completions.create(
477
+ model=st.session_state["openai_model"],
478
+ messages=[
479
+ {"role": m["role"], "content": m["content"]}
480
+ for m in st.session_state.messages #用chatbot那边的隐藏消息记录
481
+ ],
482
+ stream=True,
483
+ ):
484
+ try:
485
+ full_response += response.choices[0].delta.content
486
+ except:
487
+ full_response += ""
488
+ message_placeholder.markdown(full_response + "▌")
489
+ message_placeholder.markdown(full_response)
490
+ st.session_state.messages.append({"role": "assistant", "content": full_response})
491
+ st.session_state.messages_ui.append({"role": "assistant", "content": full_response})
492
+
493
+
494
+
495
+ if __name__ == "__main__":
496
+ app()