Download app.py from grover101/Chatbot2: direct link, hf CLI and curl.
- Browser
- Download file 4.22 kB
-
https://huggingface.co/spaces/grover101/Chatbot2/resolve/main/app.py
- Command line
-
hf download hf://spaces/grover101/Chatbot2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/grover101/Chatbot2/resolve/main/app.py
4.22 kB
| 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) |