EmbeddedAndrew commited on
Commit
cb1c674
Β·
1 Parent(s): 51450a4

import os

Browse files
Files changed (3) hide show
  1. LC_chat_w_search.py +44 -0
  2. LC_streaming.py +36 -0
  3. app.py +3 -1
LC_chat_w_search.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LC_chat_w_search.py
2
+
3
+
4
+ from langchain.callbacks import StreamlitCallbackHandler
5
+ from langchain.chat_models import ChatOpenAI
6
+ from langchain.tools import DuckDuckGoSearchRun
7
+
8
+ with st.sidebar:
9
+ openai_api_key = st.text_input("OpenAI API Key", key="langchain_search_api_key_openai", type="password")
10
+ "[Get an OpenAI API key](https://platform.openai.com/account/api-keys)"
11
+ "[View the source code](https://github.com/streamlit/llm-examples/blob/main/pages/2_Chat_with_search.py)"
12
+ "[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/streamlit/llm-examples?quickstart=1)"
13
+
14
+ st.title("πŸ”Ž LangChain - Chat with search")
15
+
16
+ """
17
+ In this example, we're using `StreamlitCallbackHandler` to display the thoughts and actions of an agent in an interactive Streamlit app.
18
+ Try more LangChain 🀝 Streamlit Agent examples at [github.com/langchain-ai/streamlit-agent](https://github.com/langchain-ai/streamlit-agent).
19
+ """
20
+
21
+ if "messages" not in st.session_state:
22
+ st.session_state["messages"] = [
23
+ {"role": "assistant", "content": "Hi, I'm a chatbot who can search the web. How can I help you?"}
24
+ ]
25
+
26
+ for msg in st.session_state.messages:
27
+ st.chat_message(msg["role"]).write(msg["content"])
28
+
29
+ if prompt := st.chat_input(placeholder="Who won the Women's U.S. Open in 2018?"):
30
+ st.session_state.messages.append({"role": "user", "content": prompt})
31
+ st.chat_message("user").write(prompt)
32
+
33
+ if not openai_api_key:
34
+ st.info("Please add your OpenAI API key to continue.")
35
+ st.stop()
36
+
37
+ llm = ChatOpenAI(model_name="gpt-3.5-turbo", openai_api_key=openai_api_key, streaming=True)
38
+ search = DuckDuckGoSearchRun(name="Search")
39
+ search_agent = initialize_agent([search], llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, handle_parsing_errors=True)
40
+ with st.chat_message("assistant"):
41
+ st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
42
+ response = search_agent.run(st.session_state.messages, callbacks=[st_cb])
43
+ st.session_state.messages.append({"role": "assistant", "content": response})
44
+ st.write(response)
LC_streaming.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LC_Streaming.py
2
+
3
+
4
+ from langchain.callbacks.base import BaseCallbackHandler
5
+ from langchain.chat_models import ChatOpenAI
6
+ from langchain.schema import HumanMessage
7
+ import streamlit as st
8
+
9
+ class StreamHandler(BaseCallbackHandler):
10
+ def __init__(self, container, initial_text="", display_method='markdown'):
11
+ self.container = container
12
+ self.text = initial_text
13
+ self.display_method = display_method
14
+
15
+ def on_llm_new_token(self, token: str, **kwargs) -> None:
16
+ self.text += token + "/"
17
+ display_function = getattr(self.container, self.display_method, None)
18
+ if display_function is not None:
19
+ display_function(self.text)
20
+ else:
21
+ raise ValueError(f"Invalid display_method: {self.display_method}")
22
+
23
+ query = st.text_input("input your query", value="Tell me a joke")
24
+ ask_button = st.button("ask")
25
+
26
+ st.markdown("### streaming box")
27
+ chat_box = st.empty()
28
+ stream_handler = StreamHandler(chat_box, display_method='write')
29
+ chat = ChatOpenAI(max_tokens=25, streaming=True, callbacks=[stream_handler])
30
+
31
+ st.markdown("### together box")
32
+
33
+ if query and ask_button:
34
+ response = chat([HumanMessage(content=query)])
35
+ llm_response = response.content
36
+ st.markdown(llm_response)
app.py CHANGED
@@ -1,9 +1,11 @@
1
  import streamlit as st
2
  from langchain.llms import OpenAI
 
 
3
 
4
  st.title('πŸ¦œπŸ”— Dev App')
5
 
6
- openai_api_key = os.environ["OPENAI_API_KEY"]#st.sidebar.text_input('OpenAI API Key')
7
 
8
  def generate_response(input_text):
9
  llm = OpenAI(temperature=0.0, openai_api_key=openai_api_key)
 
1
  import streamlit as st
2
  from langchain.llms import OpenAI
3
+ import os
4
+
5
 
6
  st.title('πŸ¦œπŸ”— Dev App')
7
 
8
+ openai_api_key = os.environ["OPENAI_API_KEY"] #st.sidebar.text_input('OpenAI API Key')
9
 
10
  def generate_response(input_text):
11
  llm = OpenAI(temperature=0.0, openai_api_key=openai_api_key)