EddyGiusepe commited on
Commit
a67cb14
·
1 Parent(s): eaf95cb

Usando streamlit

Browse files
3_streamlit_TikToken_conversation_history_limit/main.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data Scientist.: Dr. Eddy Giusepe Chirinos Isidro
3
+
4
+
5
+ Executar script
6
+ ===============
7
+
8
+ $ streamlit run main.py
9
+ """
10
+ import openai
11
+ import streamlit as st
12
+ import tiktoken
13
+ import tenacity
14
+
15
+ st.title(":orange[New Streamlit Chat Elements]")
16
+
17
+ # initialize session state
18
+ if "user_messages" not in st.session_state:
19
+ st.session_state["user_messages"] = []
20
+ if "assistant_messages" not in st.session_state:
21
+ st.session_state["assistant_messages"] = []
22
+
23
+ if "message_history" not in st.session_state:
24
+ st.session_state["message_history"] = [
25
+ {"role": "system", "content": "You are a helpful assistant."}
26
+ ]
27
+
28
+
29
+ # Define the function to count tokens
30
+ def count_tokens(text):
31
+ encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
32
+ return len(encoding.encode(text))
33
+
34
+ # Set the maximum token limit
35
+ MAX_MEMORY_TOKENS = 2000 # ou 5000
36
+
37
+ # Tenacity tente novamente 5 vezes com 2 segundos de espera cada:
38
+ @tenacity.retry(wait=tenacity.wait_fixed(2), stop=tenacity.stop_after_attempt(5))
39
+ def gpt_call(prompt, placeholder_response): # AQUI FAZEMOS A CHAMADA PARA À OpenAI.
40
+
41
+ response = openai.ChatCompletion.create(
42
+ model="gpt-3.5-turbo-0613",
43
+ stream = True,
44
+ request_timeout=30,
45
+ messages=st.session_state["message_history"],
46
+ )
47
+
48
+ # return response['choices'][0]['message']['content']
49
+ # Process the response from the API
50
+ assistant_response = ""
51
+ for chunk in response:
52
+ if "content" in chunk["choices"][0]["delta"]:
53
+ r_text = chunk["choices"][0]["delta"]["content"]
54
+ assistant_response += r_text
55
+ placeholder_response.chat_message("assistant").markdown(assistant_response, unsafe_allow_html=True)
56
+
57
+
58
+ return assistant_response
59
+
60
+
61
+ prompt = st.chat_input("Say something")
62
+ # print(len(st.session_state["user_messages"]))
63
+
64
+
65
+ if prompt:
66
+ st.session_state["user_messages"].append(prompt)
67
+ st.session_state["message_history"].append({"role": "user", "content": prompt})
68
+ prompt = st.session_state["user_messages"][-1]
69
+
70
+ total_user_messages = len(st.session_state["user_messages"])
71
+
72
+ for i in range(total_user_messages):
73
+ st.chat_message("user").write(st.session_state["user_messages"][i])
74
+
75
+ if i < total_user_messages - 1:
76
+ st.chat_message("assistant").write(st.session_state["assistant_messages"][i])
77
+ elif i == total_user_messages-1:
78
+ placeholder_response = st.empty()
79
+ st.session_state["assistant_messages"].append(gpt_call(prompt, placeholder_response))
80
+ st.session_state["message_history"].append({"role": "assistant", "content": st.session_state["assistant_messages"][-1]})
81
+
82
+ # Calculate the total tokens in the conversation history
83
+ total_tokens = sum(count_tokens(message["content"]) for message in st.session_state.message_history)
84
+
85
+ # Remove the oldest message from conversation history if total tokens exceed the maximum limit
86
+ while total_tokens > MAX_MEMORY_TOKENS:
87
+ if len(st.session_state.message_history) > 2:
88
+ removed_message = st.session_state.message_history.pop(1)
89
+ total_tokens -= count_tokens(removed_message["content"])
90
+ else:
91
+ break
92
+ st.write("total tokens: ", total_tokens)
93
+ print(st.session_state["message_history"])
94
+
95
+
3_streamlit_TikToken_conversation_history_limit/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ openai==0.27.8
2
+ streamlit==1.24.0
3
+ tiktoken==0.3.3
4
+ tenacity==8.2.2