File size: 4,218 Bytes
6de94e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a9b8de
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import os
from langchain_openai import ChatOpenAI

# Initialize ChatOpenAI without explicitly setting the API key
# It will automatically use OPENAI_API_KEY from your environment variables

from dotenv import load_dotenv
import os
from langchain_openai import ChatOpenAI

load_dotenv()  # Load environment variables from .env file
llm = ChatOpenAI(model="gpt-3.5-turbo")
import bs4
from langchain import hub
from langchain_chroma import Chroma
from langchain_community.document_loaders import WebBaseLoader
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.document_loaders import TextLoader
import gradio as gr

# Load and process documents
loader = TextLoader("cleaned_yu_sgc_content.txt", encoding='utf-8')
docs = loader.load()

text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = text_splitter.split_documents(docs)
vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())
retriever = vectorstore.as_retriever()

# Helper functions
def format_docs(docs):
    """Format documents into a single string."""
    return "\n\n".join(doc.page_content for doc in docs)

def format_chat_history(history):
    """Format chat history into a string."""
    formatted_history = ""
    for human, assistant in history:
        formatted_history += f"\nHuman: {human}\nAssistant: {assistant}"
    return formatted_history

def generate_prompt(context, question, chat_history):
    """Generate a custom prompt including chat history."""
    return f"""You are a helpful assistant designed to answer questions about Yeshiva University's Career Center.
    
    Previous conversation history:
    {chat_history}
    
    Use the following context to answer the question. If the context doesn't contain the relevant information,
    you can provide general information about career center services.

    Context: {context}

    For questions about YU Career Center services (appointments, location, assistance):
    - Use the information from the context if available
    - Include this link when relevant: [Yeshiva University Career Center](https://www.yu.edu/sgc)
    - Be specific, clear, and concise
    - Maintain consistency with previous responses in the conversation
    
    If you cannot find the answer in the context, provide a general response based on the Career Center website.
    If you cannot help at all, respond with: "Sorry, I'm not able to help with that, but feel free to ask me something else!"

    Current Question: {question}
    Response:"""


def chatbot_response(message, history):
    """Process user input and return chatbot response with history."""
    try:
        # Format the chat history
        chat_history = format_chat_history(history)
        
        # Get relevant documents
        relevant_docs = retriever.get_relevant_documents(message)
        context = format_docs(relevant_docs)
        
        # Generate the prompt with history
        prompt = generate_prompt(context, message, chat_history)
        
        # Get response from LLM
        response = llm.invoke(prompt).content
        
        return response
    except Exception as e:
        return f"I apologize, but I encountered an error: {str(e)}. Please try again."



# Create and launch Gradio interface
iface = gr.ChatInterface(
    chatbot_response,
    title="YU Career Center Assistant",
    description="""Get help with Yeshiva University Career Center services and information. 
                Ask questions about appointments, services, locations, and more.""",
    examples=[
        "How can I schedule a career counseling appointment?",
        "What services does the Career Center offer?",
        "Where is the Career Center located?",
        "What are the Career Center's hours of operation?",
        "How can I access resume writing resources?"
    ],
    theme="default"
)

# Launch the interface
print("Starting YU Career Center Chatbot...")
print("Access the interface in your browser when the URL appears.")
iface.launch(share=True)