Joshua Sundance Bailey commited on
Commit
9946cb7
β€’
1 Parent(s): b4d0284

small changes

Browse files
.env-example CHANGED
@@ -1,18 +1,10 @@
1
- JUPYTER_PORT=8181
2
 
3
  LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
4
- LANGCHAIN_API_KEY=...
5
  LANGCHAIN_TRACING_V2="true"
6
- LANGCHAIN_PROJECT="AI_GIS_language"
7
 
8
- ANYSCALE_API_KEY=...
9
  OPENAI_API_KEY=sk-...
10
- ANTHROPIC_API_KEY=...
11
-
12
- #https://github.com/streamlit/app-starter-kit
13
- #https://github.com/langchain-ai/streamlit-agent
14
- #https://github.com/hwchase17/langchain-streamlit-template
15
- #https://github.com/dataprofessor/langchain-ask-the-doc
16
- #https://github.com/dataprofessor/langchain-ask-the-data
17
- #https://github.com/dataprofessor/langchain-blog-outline-generator
18
- #https://github.com/dataprofessor/langchain-text-summarization
 
1
+ APP_PORT=8181
2
 
3
  LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
4
+ LANGCHAIN_API_KEY=ls__...
5
  LANGCHAIN_TRACING_V2="true"
6
+ LANGCHAIN_PROJECT="streamlit_chatbot"
7
 
8
+ ANYSCALE_API_KEY=secret_...
9
  OPENAI_API_KEY=sk-...
10
+ ANTHROPIC_API_KEY="sk-..."
 
 
 
 
 
 
 
 
.github/pull_request_template.md CHANGED
@@ -1,4 +1,4 @@
1
- Thank you for contributing to `AI_chatbot`.
2
  Before submitting this PR, please make sure:
3
 
4
  - [ ] Your code builds clean without any errors or warnings
 
1
+ Thank you for contributing!
2
  Before submitting this PR, please make sure:
3
 
4
  - [ ] Your code builds clean without any errors or warnings
.idea/.name ADDED
@@ -0,0 +1 @@
 
 
1
+ langchain-streamlit-demo
.idea/{AI_chatbot.iml β†’ langchain-streamlit-demo.iml} RENAMED
@@ -2,7 +2,7 @@
2
  <module type="PYTHON_MODULE" version="4">
3
  <component name="NewModuleRootManager">
4
  <content url="file://$MODULE_DIR$" />
5
- <orderEntry type="inheritedJdk" />
6
  <orderEntry type="sourceFolder" forTests="false" />
7
  </component>
8
  </module>
 
2
  <module type="PYTHON_MODULE" version="4">
3
  <component name="NewModuleRootManager">
4
  <content url="file://$MODULE_DIR$" />
5
+ <orderEntry type="jdk" jdkName="Remote Python 3.11.4 Docker (&lt;none&gt;:&lt;none&gt;) (5)" jdkType="Python SDK" />
6
  <orderEntry type="sourceFolder" forTests="false" />
7
  </component>
8
  </module>
.idea/misc.xml CHANGED
@@ -1,4 +1,4 @@
1
  <?xml version="1.0" encoding="UTF-8"?>
2
  <project version="4">
3
- <component name="ProjectRootManager" version="2" project-jdk-name="arcgis-pc (2)" project-jdk-type="Python SDK" />
4
  </project>
 
1
  <?xml version="1.0" encoding="UTF-8"?>
2
  <project version="4">
3
+ <component name="ProjectRootManager" version="2" project-jdk-name="Remote Python 3.11.4 Docker (&lt;none&gt;:&lt;none&gt;) (5)" project-jdk-type="Python SDK" />
4
  </project>
docker-compose.yml CHANGED
@@ -9,6 +9,12 @@ services:
9
  ports:
10
  - "8000:8000"
11
  volumes:
12
- - .:/home/appuser/app:rw
13
  working_dir: /home/appuser/app/
14
- entrypoint: ["python", "-m", "streamlit", "run", "${APP}", "--server.port", "8000", "--server.enableCORS", "false", "--server.address", "0.0.0.0"]
 
 
 
 
 
 
 
9
  ports:
10
  - "8000:8000"
11
  volumes:
12
+ - .:/home/appuser/app:rw
13
  working_dir: /home/appuser/app/
14
+ command: [
15
+ "python", "-m",
16
+ "streamlit", "run",
17
+ "/home/appuser/app/langchain-streamlit-demo/app.py",
18
+ "--server.port", "8000",
19
+ "--server.address", "0.0.0.0"
20
+ ]
{AI_chatbot β†’ langchain-streamlit-demo}/app.py RENAMED
@@ -1,42 +1,23 @@
1
- from datetime import datetime
2
-
3
  import streamlit as st
4
- from langchain import LLMChain
5
- from langchain.callbacks.base import BaseCallbackHandler
6
  from langchain.callbacks.tracers.langchain import wait_for_all_tracers
7
  from langchain.callbacks.tracers.run_collector import RunCollectorCallbackHandler
8
- from langchain.chat_models import ChatOpenAI
9
- from langchain.memory import StreamlitChatMessageHistory, ConversationBufferMemory
10
- from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
11
  from langchain.schema.runnable import RunnableConfig
12
- from langsmith import Client
13
- from streamlit_feedback import streamlit_feedback
 
 
 
 
 
 
 
 
14
 
15
  st.set_page_config(
16
  page_title="Chat LangSmith",
17
  page_icon="🦜",
18
  )
19
 
20
-
21
- def get_llm_chain(system_prompt: str, memory: ConversationBufferMemory) -> LLMChain:
22
- """Return a basic LLMChain with memory."""
23
- prompt = ChatPromptTemplate.from_messages(
24
- [
25
- (
26
- "system",
27
- system_prompt + "\nIt's currently {time}.",
28
- ),
29
- MessagesPlaceholder(variable_name="chat_history"),
30
- ("human", "{input}"),
31
- ],
32
- ).partial(time=lambda: str(datetime.now()))
33
- llm = ChatOpenAI(temperature=0.7, streaming=True)
34
- return LLMChain(prompt=prompt, llm=llm, memory=memory)
35
-
36
-
37
- client = Client()
38
-
39
-
40
  # "# ChatπŸ¦œπŸ› οΈ"
41
  # Initialize State
42
  if "trace_link" not in st.session_state:
@@ -49,21 +30,25 @@ st.sidebar.markdown(
49
  """,
50
  )
51
 
52
- _DEFAULT_SYSTEM_PROMPT = "You are a helpful chatbot."
53
-
54
- system_prompt = st.sidebar.text_area(
55
- "Custom Instructions",
56
- _DEFAULT_SYSTEM_PROMPT,
57
- help="Custom instructions to provide the language model to determine style, personality, etc.",
58
- )
59
- system_prompt = system_prompt.strip().replace("{", "{{").replace("}", "}}")
60
- memory = ConversationBufferMemory(
61
- chat_memory=StreamlitChatMessageHistory(key="langchain_messages"),
62
- return_messages=True,
63
- memory_key="chat_history",
64
  )
65
 
66
- chain = get_llm_chain(system_prompt, memory)
 
 
 
 
 
 
 
67
 
68
  if st.sidebar.button("Clear message history"):
69
  print("Clearing message history")
@@ -96,19 +81,6 @@ if st.session_state.trace_link:
96
  )
97
 
98
 
99
- class StreamHandler(BaseCallbackHandler):
100
- def __init__(self, container, initial_text=""):
101
- self.container = container
102
- self.text = initial_text
103
-
104
- def on_llm_new_token(self, token: str, **kwargs) -> None:
105
- self.text += token
106
- self.container.markdown(self.text)
107
-
108
-
109
- run_collector = RunCollectorCallbackHandler()
110
-
111
-
112
  def _reset_feedback():
113
  st.session_state.feedback_update = None
114
  st.session_state.feedback = None
@@ -135,59 +107,6 @@ if prompt := st.chat_input(placeholder="Ask me a question!"):
135
  url = client.read_run(run.id).url
136
  st.session_state.trace_link = url
137
 
138
- # Simple feedback section
139
- # Optionally add a thumbs up/down button for feedback
140
  if st.session_state.get("run_id"):
141
- # feedback = streamlit_feedback(
142
- # feedback_type="thumbs",
143
- # key=f"feedback_{st.session_state.run_id}",
144
- # )
145
- # scores = {"πŸ‘": 1, "πŸ‘Ž": 0}
146
- scores = {"πŸ˜€": 1, "πŸ™‚": 0.75, "😐": 0.5, "πŸ™": 0.25, "😞": 0}
147
- feedback = streamlit_feedback(
148
- feedback_type="faces",
149
- optional_text_label="[Optional] Please provide an explanation",
150
- key=f"feedback_{st.session_state.run_id}",
151
- )
152
- if feedback:
153
- score = scores[feedback["score"]]
154
- feedback = client.create_feedback(
155
- st.session_state.run_id,
156
- feedback["type"],
157
- score=score,
158
- comment=feedback.get("text", None),
159
- )
160
- st.session_state.feedback = {"feedback_id": str(feedback.id), "score": score}
161
- st.toast("Feedback recorded!", icon="πŸ“")
162
-
163
-
164
- # # Prompt for more information, if feedback was submitted
165
- # if st.session_state.get("feedback"):
166
- # feedback = st.session_state.get("feedback")
167
- # feedback_id = feedback["feedback_id"]
168
- # score = feedback["score"]
169
- # if score == 0:
170
- # if correction := st.text_input(
171
- # label="What would the correct or preferred response have been?",
172
- # key=f"correction_{feedback_id}",
173
- # ):
174
- # st.session_state.feedback_update = {
175
- # "correction": {"desired": correction},
176
- # "feedback_id": feedback_id,
177
- # }
178
- # elif score == 1:
179
- # if comment := st.text_input(
180
- # label="Anything else you'd like to add about this response?",
181
- # key=f"comment_{feedback_id}",
182
- # ):
183
- # st.session_state.feedback_update = {
184
- # "comment": comment,
185
- # "feedback_id": feedback_id,
186
- # }
187
- # # Update the feedback if additional information was provided
188
- # if st.session_state.get("feedback_update"):
189
- # feedback_update = st.session_state.get("feedback_update")
190
- # feedback_id = feedback_update.pop("feedback_id")
191
- # client.update_feedback(feedback_id, **feedback_update)
192
- # # Clear the comment or correction box
193
- # _reset_feedback()
 
 
 
1
  import streamlit as st
 
 
2
  from langchain.callbacks.tracers.langchain import wait_for_all_tracers
3
  from langchain.callbacks.tracers.run_collector import RunCollectorCallbackHandler
 
 
 
4
  from langchain.schema.runnable import RunnableConfig
5
+
6
+
7
+ from llm_stuff import (
8
+ _DEFAULT_SYSTEM_PROMPT,
9
+ get_memory,
10
+ get_llm_chain,
11
+ StreamHandler,
12
+ feedback_component,
13
+ get_langsmith_client,
14
+ )
15
 
16
  st.set_page_config(
17
  page_title="Chat LangSmith",
18
  page_icon="🦜",
19
  )
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  # "# ChatπŸ¦œπŸ› οΈ"
22
  # Initialize State
23
  if "trace_link" not in st.session_state:
 
30
  """,
31
  )
32
 
33
+ system_prompt = (
34
+ st.sidebar.text_area(
35
+ "Custom Instructions",
36
+ _DEFAULT_SYSTEM_PROMPT,
37
+ help="Custom instructions to provide the language model to determine style, personality, etc.",
38
+ )
39
+ .strip()
40
+ .replace("{", "{{")
41
+ .replace("}", "}}")
 
 
 
42
  )
43
 
44
+ memory = get_memory()
45
+
46
+ chain = get_llm_chain(memory, system_prompt)
47
+
48
+ client = get_langsmith_client()
49
+
50
+ run_collector = RunCollectorCallbackHandler()
51
+
52
 
53
  if st.sidebar.button("Clear message history"):
54
  print("Clearing message history")
 
81
  )
82
 
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  def _reset_feedback():
85
  st.session_state.feedback_update = None
86
  st.session_state.feedback = None
 
107
  url = client.read_run(run.id).url
108
  st.session_state.trace_link = url
109
 
110
+
 
111
  if st.session_state.get("run_id"):
112
+ feedback_component(client)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
langchain-streamlit-demo/llm_stuff.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+
3
+ import streamlit as st
4
+ from langchain import LLMChain
5
+ from langchain.callbacks.base import BaseCallbackHandler
6
+ from langchain.chat_models import ChatOpenAI
7
+ from langchain.memory import ConversationBufferMemory, StreamlitChatMessageHistory
8
+ from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
9
+ from streamlit_feedback import streamlit_feedback
10
+ from langsmith.client import Client
11
+
12
+ _DEFAULT_SYSTEM_PROMPT = "You are a helpful chatbot."
13
+
14
+
15
+ def get_langsmith_client():
16
+ return Client()
17
+
18
+
19
+ def get_memory() -> ConversationBufferMemory:
20
+ return ConversationBufferMemory(
21
+ chat_memory=StreamlitChatMessageHistory(key="langchain_messages"),
22
+ return_messages=True,
23
+ memory_key="chat_history",
24
+ )
25
+
26
+
27
+ def get_llm_chain(
28
+ memory: ConversationBufferMemory,
29
+ system_prompt: str = _DEFAULT_SYSTEM_PROMPT,
30
+ ) -> LLMChain:
31
+ """Return a basic LLMChain with memory."""
32
+ prompt = ChatPromptTemplate.from_messages(
33
+ [
34
+ (
35
+ "system",
36
+ system_prompt + "\nIt's currently {time}.",
37
+ ),
38
+ MessagesPlaceholder(variable_name="chat_history"),
39
+ ("human", "{input}"),
40
+ ],
41
+ ).partial(time=lambda: str(datetime.now()))
42
+ llm = ChatOpenAI(temperature=0.7, streaming=True)
43
+ return LLMChain(prompt=prompt, llm=llm, memory=memory or get_memory())
44
+
45
+
46
+ class StreamHandler(BaseCallbackHandler):
47
+ def __init__(self, container, initial_text=""):
48
+ self.container = container
49
+ self.text = initial_text
50
+
51
+ def on_llm_new_token(self, token: str, **kwargs) -> None:
52
+ self.text += token
53
+ self.container.markdown(self.text)
54
+
55
+
56
+ def feedback_component(client):
57
+ scores = {"πŸ˜€": 1, "πŸ™‚": 0.75, "😐": 0.5, "πŸ™": 0.25, "😞": 0}
58
+ if feedback := streamlit_feedback(
59
+ feedback_type="faces",
60
+ optional_text_label="[Optional] Please provide an explanation",
61
+ key=f"feedback_{st.session_state.run_id}",
62
+ ):
63
+ score = scores[feedback["score"]]
64
+ feedback = client.create_feedback(
65
+ st.session_state.run_id,
66
+ feedback["type"],
67
+ score=score,
68
+ comment=feedback.get("text", None),
69
+ )
70
+ st.session_state.feedback = {"feedback_id": str(feedback.id), "score": score}
71
+ st.toast("Feedback recorded!", icon="πŸ“")