-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.py
248 lines (200 loc) Β· 9.03 KB
/
main.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
# If trying this app locally, comment out these 3 lines
__import__("pysqlite3")
import sys
sys.modules["sqlite3"] = sys.modules.pop("pysqlite3")
import os
import streamlit as st
from langchain.callbacks.tracers.langchain import wait_for_all_tracers
from langchain.callbacks.tracers.run_collector import RunCollectorCallbackHandler
from langchain.memory import ConversationBufferMemory, StreamlitChatMessageHistory
from langchain.schema.runnable import RunnableConfig
from langsmith import Client
from streamlit_feedback import streamlit_feedback
from essential_chain import initialize_chain
from vanilla_chain import get_llm_chain
st.set_page_config(
page_title="Chat with the Streamlit docs via LangChain, Collect user feedback via Trubrics and LangSmith!",
page_icon="π¦",
)
# ... [rest of the code above]
# Set LangSmith environment variables
os.environ["OPENAI_API_KEY"] = st.secrets["api_keys"]["OPENAI_API_KEY"]
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
# Add the toggle for LangSmith API key source
use_secret_key = st.sidebar.toggle(label="Demo LangSmith API key", value=True)
# Conditionally set the project name based on the toggle
if use_secret_key:
os.environ["LANGCHAIN_PROJECT"] = "Streamlit Demo"
else:
project_name = st.sidebar.text_input(
"Name your LangSmith Project:", value="Streamlit Demo"
)
os.environ["LANGCHAIN_PROJECT"] = project_name
# Conditionally get the API key based on the toggle
if use_secret_key:
langchain_api_key = st.secrets["api_keys"][
"LANGSMITH_API_KEY"
] # assuming it's stored under this key in secrets
else:
langchain_api_key = st.sidebar.text_input(
"π Add your LangSmith Key",
value="",
placeholder="Your_LangSmith_Key_Here",
label_visibility="collapsed",
)
if langchain_api_key is not None:
os.environ["LANGCHAIN_API_KEY"] = langchain_api_key
if "last_run" not in st.session_state:
st.session_state["last_run"] = "some_initial_value"
langchain_endpoint = "https://api.smith.langchain.com"
col1, col2, col3 = st.columns([0.6, 3, 1])
with col2:
st.image("images/logo.png", width=460)
st.write("")
st.markdown("**β¨ Chat with the Streamlit docs via [:blue[LangChain]](https://www.langchain.com/)** πͺ **Collect user feedback via [:orange[Trubrics]](https://github.com/trubrics/streamlit-feedback) and [:green[LangSmith]](https://www.langchain.com/langsmith)**")
st.markdown("___")
st.write("π Ask a question about the [Streamlit docs](https://docs.streamlit.io/) or π‘ Check out the tutorial to build this app in our [blog post](https://blog.streamlit.io/how-in-app-feedback-can-increase-your-chatbots-performance/)")
# Check if the LangSmith API key is provided
if not langchain_api_key or langchain_api_key.strip() == "Your_LangSmith_Key_Here":
st.info("β οΈ Add your [LangSmith API key](https://python.langchain.com/docs/guides/langsmith/walkthrough) to continue, or switch to the Demo key")
else:
client = Client(api_url=langchain_endpoint, api_key=langchain_api_key)
# Initialize State
if "trace_link" not in st.session_state:
st.session_state.trace_link = None
if "run_id" not in st.session_state:
st.session_state.run_id = None
_DEFAULT_SYSTEM_PROMPT = ""
system_prompt = _DEFAULT_SYSTEM_PROMPT = ""
system_prompt = system_prompt.strip().replace("{", "{{").replace("}", "}}")
chain_type = st.sidebar.radio(
"Choose your LLM:",
("Classic `GPT 3.5` LLM", "RAG LLM for Streamlit Docs β¨"),
index=1,
)
memory = ConversationBufferMemory(
chat_memory=StreamlitChatMessageHistory(key="langchain_messages"),
return_messages=True,
memory_key="chat_history",
)
if chain_type == "Classic `GPT 3.5` LLM":
chain = get_llm_chain(system_prompt, memory)
else: # This will be triggered when "RAG LLM for Streamlit Docs β¨" is selected
chain = initialize_chain(system_prompt, _memory=memory)
if st.sidebar.button("Clear message history"):
print("Clearing message history")
memory.clear()
st.session_state.trace_link = None
st.session_state.run_id = None
# NOTE: This won't be necessary for Streamlit 1.26+, you can just pass the type directly
# https://github.com/streamlit/streamlit/pull/7094
def _get_openai_type(msg):
if msg.type == "human":
return "user"
if msg.type == "ai":
return "assistant"
if msg.type == "chat":
return msg.role
return msg.type
for msg in st.session_state.langchain_messages:
streamlit_type = _get_openai_type(msg)
avatar = "π¦" if streamlit_type == "assistant" else None
with st.chat_message(streamlit_type, avatar=avatar):
st.markdown(msg.content)
run_collector = RunCollectorCallbackHandler()
runnable_config = RunnableConfig(
callbacks=[run_collector],
tags=["Streamlit Chat"],
)
if st.session_state.trace_link:
st.sidebar.markdown(
f'<a href="{st.session_state.trace_link}" target="_blank"><button>Latest Trace: π οΈ</button></a>',
unsafe_allow_html=True,
)
def _reset_feedback():
st.session_state.feedback_update = None
st.session_state.feedback = None
MAX_CHAR_LIMIT = 500 # Adjust this value as needed
if prompt := st.chat_input(placeholder="Ask a question about the Streamlit docs!"):
if len(prompt) > MAX_CHAR_LIMIT:
st.warning(f"β οΈ Your input is too long! Please limit your input to {MAX_CHAR_LIMIT} characters.")
prompt = None # Reset the prompt so it doesn't get processed further
else:
st.chat_message("user").write(prompt)
_reset_feedback()
with st.chat_message("assistant", avatar="π¦"):
message_placeholder = st.empty()
full_response = ""
input_structure = {"input": prompt}
if chain_type == "RAG LLM for Streamlit Docs β¨":
input_structure = {
"question": prompt,
"chat_history": [
(msg.type, msg.content)
for msg in st.session_state.langchain_messages
],
}
if chain_type == "Classic `GPT 3.5` LLM":
message_placeholder.markdown("thinking...")
full_response = chain.invoke(input_structure, config=runnable_config)[
"text"
]
else:
for chunk in chain.stream(input_structure, config=runnable_config):
full_response += chunk["answer"] # Updated to use the 'answer' key
message_placeholder.markdown(full_response + "β")
memory.save_context({"input": prompt}, {"output": full_response})
message_placeholder.markdown(full_response)
# The run collector will store all the runs in order. We'll just take the root and then
# reset the list for next interaction.
run = run_collector.traced_runs[0]
run_collector.traced_runs = []
st.session_state.run_id = run.id
wait_for_all_tracers()
# Requires langsmith >= 0.0.19
url = client.share_run(run.id)
# Or if you just want to use this internally
# without sharing
# url = client.read_run(run.id).url
st.session_state.trace_link = url
has_chat_messages = len(st.session_state.get("langchain_messages", [])) > 0
# Only show the feedback toggle if there are chat messages
if has_chat_messages:
feedback_option = (
"faces" if st.toggle(label="`Thumbs` β `Faces`", value=False) else "thumbs"
)
else:
pass
if st.session_state.get("run_id"):
feedback = streamlit_feedback(
feedback_type=feedback_option, # Use the selected feedback option
optional_text_label="[Optional] Please provide an explanation", # Adding a label for optional text input
key=f"feedback_{st.session_state.run_id}",
)
# Define score mappings for both "thumbs" and "faces" feedback systems
score_mappings = {
"thumbs": {"π": 1, "π": 0},
"faces": {"π": 1, "π": 0.75, "π": 0.5, "π": 0.25, "π": 0},
}
# Get the score mapping based on the selected feedback option
scores = score_mappings[feedback_option]
if feedback:
# Get the score from the selected feedback option's score mapping
score = scores.get(feedback["score"])
if score is not None:
# Formulate feedback type string incorporating the feedback option and score value
feedback_type_str = f"{feedback_option} {feedback['score']}"
# Record the feedback with the formulated feedback type string and optional comment
feedback_record = client.create_feedback(
st.session_state.run_id,
feedback_type_str, # Updated feedback type
score=score,
comment=feedback.get("text"),
)
st.session_state.feedback = {
"feedback_id": str(feedback_record.id),
"score": score,
}
else:
st.warning("Invalid feedback score.")