seansullivan commited on
Commit
19ca162
·
verified ·
1 Parent(s): 7ef9d33

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +218 -0
app.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from getpass import getpass
2
+ from langchain_openai import OpenAIEmbeddings
3
+
4
+ from pinecone import Pinecone
5
+
6
+ from pinecone_text.sparse import SpladeEncoder
7
+ from langchain_community.retrievers import PineconeHybridSearchRetriever
8
+
9
+ import os
10
+
11
+ from langchain_core.output_parsers import StrOutputParser
12
+ from langchain_core.prompts import ChatPromptTemplate
13
+ from langchain_core.runnables import RunnableParallel, RunnablePassthrough, Runnable
14
+ from langchain_anthropic import ChatAnthropic
15
+ from langchain.retrievers import EnsembleRetriever
16
+
17
+ import streamlit as st
18
+
19
+ # Streamlit App Configuration (gets model_name, index_name, namespace_name before needed)
20
+ st.set_page_config(page_title="Chat with any Documentation Website", page_icon="🟩")
21
+ st.markdown("<h1 style='text-align: center;'>Select your website and begin chatting:</h1>", unsafe_allow_html=True)
22
+
23
+ model_name = "claude-3-haiku-20240307"
24
+
25
+
26
+ namespace_name = st.sidebar.selectbox("Choose a Website", ("Langchain", "Apify", "HiperGator", "Crawlee", "QDRANT", "Supabase", "Zapier"))
27
+
28
+ namespace_name2 = st.sidebar.selectbox("Choose a Website", ("","Langchain","Apify", "HiperGator", "Crawlee", "QDRANT", "Supabase", "Zapier"))
29
+
30
+ namespace_name3 = st.sidebar.selectbox("Choose a Website", ("","Langchain","Apify", "Crawlee", "QDRANT", "Supabase", "Zapier"))
31
+
32
+
33
+ # ========== PART 1 ==========
34
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
35
+ ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
36
+ PINE_API_KEY = os.getenv("PINE_API_KEY")
37
+
38
+ embed = OpenAIEmbeddings(
39
+ model='text-embedding-3-small',
40
+ openai_api_key=OPENAI_API_KEY,
41
+ dimensions = 768
42
+ )
43
+
44
+
45
+ # ========== PART 2 ==========
46
+ index_name='splade'
47
+ pc = Pinecone(api_key=PINE_API_KEY)
48
+ index = pc.Index(index_name)
49
+
50
+ # ========== PART 3 ==========
51
+
52
+
53
+ splade_encoder = SpladeEncoder()
54
+ retriever1 = PineconeHybridSearchRetriever(
55
+ embeddings=embed, sparse_encoder=splade_encoder, index=index, namespace=namespace_name, top_k=2
56
+ )
57
+ retriever2 = PineconeHybridSearchRetriever(
58
+ embeddings=embed, sparse_encoder=splade_encoder, index=index, namespace=namespace_name2, top_k=2
59
+ )
60
+ retriever3 = PineconeHybridSearchRetriever(
61
+ embeddings=embed, sparse_encoder=splade_encoder, index=index, namespace=namespace_name3, top_k=2
62
+ )
63
+
64
+ retriever = EnsembleRetriever(
65
+ retrievers=[retriever1, retriever2, retriever3], weights=[0.5,0.5,0.5]
66
+ )
67
+
68
+
69
+ LANGCHAIN_TRACING_V2 = os.getenv('LANGCHAIN_TRACING_V2')
70
+
71
+ LANGCHAIN_ENDPOINT = os.getenv('LANGCHAIN_ENDPOINT')
72
+
73
+ LANGCHAIN_PROJECT = os.getenv('LANGCHAIN_PROJECT')
74
+
75
+ LANGCHAIN_API_KEY = os.getenv('LANGCHAIN_API_KEY')
76
+
77
+
78
+ # ========== PART 4 ==========
79
+ # RAG prompt
80
+ prefix = f"You are an expert in {namespace_name} documentation. Your purpose is to provide concise, accurate assistance to the user's specific question using only the context provided from the official {namespace_name} documentation.\n"
81
+
82
+ template = prefix + \
83
+ """
84
+ Restrictions and guidelines:
85
+ - Focus solely on answering the user's direct question. Do not deviate to tangential topics.
86
+ - Base your response entirely on the provided documentation context. If the question cannot be answered from the given context, state that you do not have enough information to answer based on the excerpt provided.
87
+ - Refrain from making assumptions, inferences or providing information beyond what is explicitly stated in the documentation.
88
+ - Use precise technical language from the documentation. Avoid oversimplification.
89
+ - Do not mention being an AI language model or refer to your own training or knowledge cutoff.
90
+ - Format any code examples, commands, or file paths appropriately.
91
+ - Let the user know if additional context is needed for a more complete answer.
92
+ User's Question:
93
+ {question}
94
+ Documentation context:
95
+ {context}
96
+ """
97
+
98
+ prompt = ChatPromptTemplate.from_template(template)
99
+
100
+ # Haiku
101
+ model = ChatAnthropic(temperature=0, anthropic_api_key=ANTHROPIC_API_KEY, model_name="claude-3-haiku-20240307")
102
+
103
+ class SourceDedup(Runnable):
104
+ def invoke(self, input, config=None):
105
+ assert isinstance(input, dict)
106
+ documents = input["context"]
107
+ unique_sources = set()
108
+ unique_documents = []
109
+
110
+ for doc in documents:
111
+ source = doc.metadata["source"]
112
+ if source not in unique_sources:
113
+ unique_sources.add(source)
114
+ unique_documents.append(doc)
115
+ input["context"] = unique_documents
116
+ return input
117
+
118
+ class PassParentContent(Runnable):
119
+ def invoke(self, input, config=None):
120
+ assert isinstance(input, dict)
121
+ documents = input["context"]
122
+
123
+ for doc in documents:
124
+ if "parent_content" in doc.metadata:
125
+ doc.page_content = doc.metadata["parent_content"]
126
+ return input
127
+
128
+ rag_chain = (
129
+ RunnablePassthrough()
130
+ | SourceDedup()
131
+ | PassParentContent()
132
+ | prompt
133
+ | model
134
+ | StrOutputParser()
135
+ )
136
+
137
+ rag_chain_with_source = RunnableParallel(
138
+ {"context": retriever, "question": RunnablePassthrough()}
139
+ ).assign(answer=rag_chain)
140
+
141
+ def generate_response(prompt):
142
+ start = ""
143
+ st.session_state['generated'].append(start)
144
+ yield start
145
+
146
+ all_sources = []
147
+ for chunk in rag_chain_with_source.stream(prompt):
148
+
149
+ if list(chunk.keys())[0] == 'answer':
150
+ st.session_state['generated'][-1] += chunk['answer']
151
+ yield chunk['answer']
152
+
153
+ elif list(chunk.keys())[0] == 'context':
154
+ pass
155
+ # Sources DO NOT work the same with this code... removing for now.
156
+ sources = chunk['context']
157
+ for thing in chunk['context']:
158
+ print()
159
+ print(thing.metadata)
160
+ sources = [doc.metadata['source'] for doc in chunk['context']]
161
+ all_sources.extend(sources)
162
+
163
+ formatted_response = f"\n\nSources:\n" + "\n".join(all_sources)
164
+ yield formatted_response
165
+
166
+ # question = "How can I do hybrid search with a pinecone database?"
167
+ # answer = generate_response(question)
168
+ # print(answer)
169
+
170
+ # ==================== THE REST OF THE STREAMLIT APP ====================
171
+
172
+ # Initialize session state variables if they don't exist
173
+ if 'generated' not in st.session_state:
174
+ st.session_state['generated'] = []
175
+
176
+ if 'past' not in st.session_state:
177
+ st.session_state['past'] = []
178
+
179
+ if 'messages' not in st.session_state:
180
+ st.session_state['messages'] = [{"role": "system", "content": "You are a helpful assistant."}]
181
+
182
+ if 'total_cost' not in st.session_state:
183
+ st.session_state['total_cost'] = 0.0
184
+
185
+ def refresh_text():
186
+ with response_container:
187
+ for i in range(len(st.session_state['past'])):
188
+ try:
189
+ user_message_content = st.session_state["past"][i]
190
+ message = st.chat_message("user")
191
+ message.write(user_message_content)
192
+ except:
193
+ print("Past error")
194
+
195
+ try:
196
+ ai_message_content = st.session_state["generated"][i]
197
+ message = st.chat_message("assistant")
198
+ message.write(ai_message_content)
199
+ except:
200
+ print("Generated Error")
201
+
202
+ response_container = st.container()
203
+ container = st.container()
204
+
205
+ if prompt := st.chat_input("Ask a question..."):
206
+ st.session_state['past'].append(prompt)
207
+ refresh_text()
208
+
209
+ st.session_state['messages'].append({"role": "user", "content": prompt})
210
+ with response_container:
211
+ my_generator = generate_response(prompt)
212
+ message = st.chat_message("assistant")
213
+ message.write_stream(my_generator)
214
+
215
+ if __name__ == "__main__":
216
+ #result = retriever.get_relevant_documents("foo")
217
+ #print(result[0].page_content)
218
+ pass