Spaces:
Sleeping
Sleeping
File size: 1,739 Bytes
232d531 57cd8e9 232d531 6fd8a6a 232d531 7908dfb 6fd8a6a 7908dfb 57cd8e9 6fd8a6a 57cd8e9 6fd8a6a 57cd8e9 6e5e4ed 6fd8a6a 57cd8e9 6fd8a6a 57cd8e9 232d531 6fd8a6a 232d531 6fd8a6a 232d531 57cd8e9 588455e 232d531 6fd8a6a 232d531 588455e |
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.memory import ConversationBufferMemory
from langchain.chat_models import ChatOpenAI
from langchain_community.chat_message_histories import StreamlitChatMessageHistory
import streamlit as st
import os
from dotenv import load_dotenv
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# Initialize Streamlit app
st.set_page_config(page_title="LangChain Chatbot with Memory")
st.title("🤖 LangChain Chatbot with Memory")
# Initialize chat message history
history = StreamlitChatMessageHistory(key="chat_messages")
# Display chat history
for msg in history.messages:
if msg.type == "human":
st.chat_message("user").write(msg.content)
else:
st.chat_message("assistant").write(msg.content)
# Memory
memory = ConversationBufferMemory(
memory_key="chat_history",
chat_memory=history,
return_messages=True
)
# Prompt with system role + instruction
prompt = PromptTemplate(
input_variables=["chat_history", "input"],
template="""
You are a friendly and knowledgeable assistant.
Always reply in a complete sentence using no more than 50 words.
Conversation so far:
{chat_history}
User: {input}
Assistant:"""
)
# LLM and chain
llm = ChatOpenAI(
openai_api_key=OPENAI_API_KEY,
model_name="gpt-4o-mini",
temperature=0.7,
max_tokens=50
)
conversation = LLMChain(
llm=llm,
prompt=prompt,
memory=memory
)
# Input from user
if prompt_input := st.chat_input("Say something..."):
st.chat_message("user").write(prompt_input)
# Let LangChain handle history
response = conversation.run(input=prompt_input)
st.chat_message("assistant").write(response)
|