Adding streamlit chatbot

This commit is contained in:
Cole Medin
2024-07-02 07:53:06 -05:00
parent 74763f1e0e
commit 3f8afcf526
3 changed files with 65 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
# Rename this file to .env once you have filled in the below environment variables!
# Get your Open AI API Key by following these instructions -
# https://help.openai.com/en/articles/4936850-where-do-i-find-my-openai-api-key
# You only need this environment variable set if you set LLM_MODEL to a GPT model
OPENAI_API_KEY=
# See all Open AI models you can use here -
# https://platform.openai.com/docs/models
# A good default to go with here is gpt-4o
LLM_MODEL=gpt-4o

View File

@@ -0,0 +1,7 @@
openai==1.10.0
python-dotenv==0.13.0
langchain==0.2.6
langchain-community==0.2.6
langchain-core==0.2.10
langchain-openai==0.1.10
streamlit==1.36.0

View File

@@ -0,0 +1,47 @@
from dotenv import load_dotenv
from datetime import datetime
import streamlit as st
import json
import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import AIMessage, SystemMessage, HumanMessage, ToolMessage
load_dotenv()
model = os.getenv('LLM_MODEL', 'gpt-4o')
def main():
st.title("Streamlit Chatbot")
# Initialize the chat history with the initial system message
if "messages" not in st.session_state:
st.session_state.messages = [
SystemMessage(content=f"The current date is: {datetime.now().date()}")
]
# Display chat messages from history each time the script is rerun when the UI state changes
for message in st.session_state.messages:
message_json = json.loads(message.json())
with st.chat_message(message_json["type"]):
st.markdown(message_json["content"])
# Assign prompt to the user input if any is given, otherwise skip everything in this if statement
if prompt := st.chat_input("What would you like to do today?"):
# Display user message in chat message container
st.chat_message("user").markdown(prompt)
# Add the user message to chat history
st.session_state.messages.append(HumanMessage(content=prompt))
# Display the chatbot's response in chat message container
with st.chat_message("assistant"):
chatbot = ChatOpenAI(model=model)
stream = chatbot.stream(st.session_state.messages)
response = st.write_stream(stream)
st.session_state.messages.append(AIMessage(content=response))
if __name__ == "__main__":
main()