File size: 1,741 Bytes
a7bb503
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9b17f1
 
 
 
a7bb503
 
 
52fcaa0
a7bb503
 
d9b17f1
 
a7bb503
 
 
 
 
 
 
 
 
 
 
 
d9b17f1
a7bb503
d9b17f1
 
 
 
 
 
 
 
 
a7bb503
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
from langchain.schema import HumanMessage, SystemMessage, AIMessage
from langchain_community.chat_models import ChatOpenAI
import os
import streamlit as st

st.set_page_config(page_title="Conversational Chatbot", page_icon="πŸ’¬")

st.title("πŸ’¬ A Langchain Chatbot")
st.caption("πŸš€ A chatbot powered by OpenAI LLM")

# Set your OpenAI API key here
#os.environ["OPENAI_API_KEY"] = "your_api_key"

# User input OpenAI API key
api_key = st.sidebar.text_input("Enter OpenAI API Key:", key="api_key", type="password")

chat = None  # Define chat object

if api_key:  # Check if API key is provided
    chat = ChatOpenAI(api_key=api_key, temperature=0.5)  # Create ChatOpenAI instance

if 'messages' not in st.session_state:
    st.session_state['messages'] = [
        SystemMessage(content="Hello, I am a chatbot to help you with your queries. How can I help you !?")
    ]

st.write(st.session_state['messages'][0].content)

def get_openai_response(query):
    st.session_state['messages'].append(HumanMessage(content=query))
    answer = chat(st.session_state['messages'])
    st.session_state['messages'].append(AIMessage(content=answer.content))

    return answer.content


description = "Enter your query here..."
input_text = st.text_input("Input: ", value="", key="input", placeholder=description)

if st.button("Submit"):
    if chat is None:
        st.warning("Please input your OpenAI API key.")
    elif not input_text.strip():
        st.warning("Please enter a query.")
    else:
        try:
            with st.spinner('Generating...'):
                response = get_openai_response(input_text)
                st.write(response)
        except Exception as e:
            st.error("Please enter a valid OpenAI API key.")