rianders Nishitha-Chidipothu commited on
Commit
6d4d839
β€’
1 Parent(s): af4dc9a

Upload chatbot_streamlit.py (#1)

Browse files

- Upload chatbot_streamlit.py (fae0cb55b3b11308c1db84b8856d805c4bdcb75e)


Co-authored-by: Nishitha Chidipothu <Nishitha-Chidipothu@users.noreply.huggingface.co>

Files changed (1) hide show
  1. chatbot_streamlit.py +60 -0
chatbot_streamlit.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ from io import StringIO
5
+ import asyncio
6
+
7
+
8
+ from langchain.agents import initialize_agent, AgentType
9
+ from langchain_community.callbacks import StreamlitCallbackHandler
10
+ from langchain_community.tools import DuckDuckGoSearchRun
11
+ from langchain_openai import ChatOpenAI
12
+
13
+ api_key = st.secrets["OPENAI_API_KEY"]
14
+
15
+
16
+ with st.sidebar:
17
+ "[Get an OpenAI API key](https://platform.openai.com/account/api-keys)"
18
+ "[View the source code](https://github.com/streamlit/llm-examples/blob/main/pages/2_Chat_with_search.py)"
19
+ "[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/streamlit/llm-examples?quickstart=1)"
20
+
21
+ st.title("πŸ”Ž LangChain - Chat with search")
22
+
23
+ """
24
+ In this example, we're using `StreamlitCallbackHandler` to display the thoughts and actions of an agent in an interactive Streamlit app.
25
+ Try more LangChain 🀝 Streamlit Agent examples at [github.com/langchain-ai/streamlit-agent](https://github.com/langchain-ai/streamlit-agent).
26
+ """
27
+
28
+ if "messages" not in st.session_state:
29
+ st.session_state["messages"] = [
30
+ {"role": "assistant", "content": "Hi, I'm a chatbot who is trying to answer your questions"}
31
+ ]
32
+
33
+ for msg in st.session_state.messages:
34
+ st.chat_message(msg["role"]).write(msg["content"])
35
+
36
+ if prompt := st.chat_input(placeholder="Who won the Women's U.S. Open in 2018?"):
37
+ st.session_state.messages.append({"role": "user", "content": prompt})
38
+ st.chat_message("user").write(prompt)
39
+
40
+ if not api_key:
41
+ st.info("Please add your OpenAI API key to continue.")
42
+ st.stop()
43
+
44
+ llm = ChatOpenAI(model_name="gpt-3.5-turbo", openai_api_key=api_key, streaming=True)
45
+ Search = DuckDuckGoSearchRun(name="Search")
46
+
47
+ # Create a new event loop
48
+ loop = asyncio.new_event_loop()
49
+ asyncio.set_event_loop(loop)
50
+
51
+ search_agent = initialize_agent([Search], llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, handle_parsing_errors=True)
52
+
53
+
54
+
55
+
56
+ with st.chat_message("assistant"):
57
+ st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
58
+ response = search_agent.run(st.session_state.messages, callbacks=[st_cb])
59
+ st.session_state.messages.append({"role": "assistant", "content": response})
60
+ st.write(response)