grover101 commited on
Commit
6de94e2
·
verified ·
1 Parent(s): 79709bf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -104
app.py CHANGED
@@ -1,105 +1,111 @@
1
- import os
2
- from langchain_openai import ChatOpenAI
3
-
4
- # Initialize ChatOpenAI without explicitly setting the API key
5
- # It will automatically use OPENAI_API_KEY from your environment variables
6
- llm = ChatOpenAI(model="gpt-3.5-turbo")
7
- import bs4
8
- from langchain import hub
9
- from langchain_chroma import Chroma
10
- from langchain_community.document_loaders import WebBaseLoader
11
- from langchain_core.output_parsers import StrOutputParser
12
- from langchain_core.runnables import RunnablePassthrough
13
- from langchain_openai import OpenAIEmbeddings
14
- from langchain_text_splitters import RecursiveCharacterTextSplitter
15
- from langchain.document_loaders import TextLoader
16
- import gradio as gr
17
-
18
- # Load and process documents
19
- loader = TextLoader("cleaned_yu_sgc_content.txt", encoding='utf-8')
20
- docs = loader.load()
21
-
22
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
23
- splits = text_splitter.split_documents(docs)
24
- vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())
25
- retriever = vectorstore.as_retriever()
26
-
27
- # Helper functions
28
- def format_docs(docs):
29
- """Format documents into a single string."""
30
- return "\n\n".join(doc.page_content for doc in docs)
31
-
32
- def format_chat_history(history):
33
- """Format chat history into a string."""
34
- formatted_history = ""
35
- for human, assistant in history:
36
- formatted_history += f"\nHuman: {human}\nAssistant: {assistant}"
37
- return formatted_history
38
-
39
- def generate_prompt(context, question, chat_history):
40
- """Generate a custom prompt including chat history."""
41
- return f"""You are a helpful assistant designed to answer questions about Yeshiva University's Career Center.
42
-
43
- Previous conversation history:
44
- {chat_history}
45
-
46
- Use the following context to answer the question. If the context doesn't contain the relevant information,
47
- you can provide general information about career center services.
48
-
49
- Context: {context}
50
-
51
- For questions about YU Career Center services (appointments, location, assistance):
52
- - Use the information from the context if available
53
- - Include this link when relevant: [Yeshiva University Career Center](https://www.yu.edu/sgc)
54
- - Be specific, clear, and concise
55
- - Maintain consistency with previous responses in the conversation
56
-
57
- If you cannot find the answer in the context, provide a general response based on the Career Center website.
58
- 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!"
59
-
60
- Current Question: {question}
61
- Response:"""
62
-
63
-
64
- def chatbot_response(message, history):
65
- """Process user input and return chatbot response with history."""
66
- try:
67
- # Format the chat history
68
- chat_history = format_chat_history(history)
69
-
70
- # Get relevant documents
71
- relevant_docs = retriever.get_relevant_documents(message)
72
- context = format_docs(relevant_docs)
73
-
74
- # Generate the prompt with history
75
- prompt = generate_prompt(context, message, chat_history)
76
-
77
- # Get response from LLM
78
- response = llm.invoke(prompt).content
79
-
80
- return response
81
- except Exception as e:
82
- return f"I apologize, but I encountered an error: {str(e)}. Please try again."
83
-
84
-
85
-
86
- # Create and launch Gradio interface
87
- iface = gr.ChatInterface(
88
- chatbot_response,
89
- title="YU Career Center Assistant",
90
- description="""Get help with Yeshiva University Career Center services and information.
91
- Ask questions about appointments, services, locations, and more.""",
92
- examples=[
93
- "How can I schedule a career counseling appointment?",
94
- "What services does the Career Center offer?",
95
- "Where is the Career Center located?",
96
- "What are the Career Center's hours of operation?",
97
- "How can I access resume writing resources?"
98
- ],
99
- theme="default"
100
- )
101
-
102
- # Launch the interface
103
- print("Starting YU Career Center Chatbot...")
104
- print("Access the interface in your browser when the URL appears.")
 
 
 
 
 
 
105
  iface.launch(share=True)
 
1
+ import os
2
+ from langchain_openai import ChatOpenAI
3
+
4
+ # Initialize ChatOpenAI without explicitly setting the API key
5
+ # It will automatically use OPENAI_API_KEY from your environment variables
6
+
7
+ from dotenv import load_dotenv
8
+ import os
9
+ from langchain_openai import ChatOpenAI
10
+
11
+ load_dotenv() # Load environment variables from .env file
12
+ llm = ChatOpenAI(model="gpt-3.5-turbo")
13
+ import bs4
14
+ from langchain import hub
15
+ from langchain_chroma import Chroma
16
+ from langchain_community.document_loaders import WebBaseLoader
17
+ from langchain_core.output_parsers import StrOutputParser
18
+ from langchain_core.runnables import RunnablePassthrough
19
+ from langchain_openai import OpenAIEmbeddings
20
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
21
+ from langchain.document_loaders import TextLoader
22
+ import gradio as gr
23
+
24
+ # Load and process documents
25
+ loader = TextLoader("cleaned_yu_sgc_content.txt", encoding='utf-8')
26
+ docs = loader.load()
27
+
28
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
29
+ splits = text_splitter.split_documents(docs)
30
+ vectorstore = Chroma.from_documents(documents=splits, embedding=OpenAIEmbeddings())
31
+ retriever = vectorstore.as_retriever()
32
+
33
+ # Helper functions
34
+ def format_docs(docs):
35
+ """Format documents into a single string."""
36
+ return "\n\n".join(doc.page_content for doc in docs)
37
+
38
+ def format_chat_history(history):
39
+ """Format chat history into a string."""
40
+ formatted_history = ""
41
+ for human, assistant in history:
42
+ formatted_history += f"\nHuman: {human}\nAssistant: {assistant}"
43
+ return formatted_history
44
+
45
+ def generate_prompt(context, question, chat_history):
46
+ """Generate a custom prompt including chat history."""
47
+ return f"""You are a helpful assistant designed to answer questions about Yeshiva University's Career Center.
48
+
49
+ Previous conversation history:
50
+ {chat_history}
51
+
52
+ Use the following context to answer the question. If the context doesn't contain the relevant information,
53
+ you can provide general information about career center services.
54
+
55
+ Context: {context}
56
+
57
+ For questions about YU Career Center services (appointments, location, assistance):
58
+ - Use the information from the context if available
59
+ - Include this link when relevant: [Yeshiva University Career Center](https://www.yu.edu/sgc)
60
+ - Be specific, clear, and concise
61
+ - Maintain consistency with previous responses in the conversation
62
+
63
+ If you cannot find the answer in the context, provide a general response based on the Career Center website.
64
+ 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!"
65
+
66
+ Current Question: {question}
67
+ Response:"""
68
+
69
+
70
+ def chatbot_response(message, history):
71
+ """Process user input and return chatbot response with history."""
72
+ try:
73
+ # Format the chat history
74
+ chat_history = format_chat_history(history)
75
+
76
+ # Get relevant documents
77
+ relevant_docs = retriever.get_relevant_documents(message)
78
+ context = format_docs(relevant_docs)
79
+
80
+ # Generate the prompt with history
81
+ prompt = generate_prompt(context, message, chat_history)
82
+
83
+ # Get response from LLM
84
+ response = llm.invoke(prompt).content
85
+
86
+ return response
87
+ except Exception as e:
88
+ return f"I apologize, but I encountered an error: {str(e)}. Please try again."
89
+
90
+
91
+
92
+ # Create and launch Gradio interface
93
+ iface = gr.ChatInterface(
94
+ chatbot_response,
95
+ title="YU Career Center Assistant",
96
+ description="""Get help with Yeshiva University Career Center services and information.
97
+ Ask questions about appointments, services, locations, and more.""",
98
+ examples=[
99
+ "How can I schedule a career counseling appointment?",
100
+ "What services does the Career Center offer?",
101
+ "Where is the Career Center located?",
102
+ "What are the Career Center's hours of operation?",
103
+ "How can I access resume writing resources?"
104
+ ],
105
+ theme="default"
106
+ )
107
+
108
+ # Launch the interface
109
+ print("Starting YU Career Center Chatbot...")
110
+ print("Access the interface in your browser when the URL appears.")
111
  iface.launch(share=True)