-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
258 lines (177 loc) · 7.27 KB
/
main.py
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
from fastapi import FastAPI, HTTPException, Request, Form
from fastapi.responses import JSONResponse, HTMLResponse
from pydantic import BaseModel
from fastapi.templating import Jinja2Templates
from fastapi.responses import RedirectResponse
from dotenv import load_dotenv
import os
from langchain_community.vectorstores import Chroma
from langchain_community.document_loaders import WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
import chromadb
app = FastAPI()
load_dotenv()
templates = Jinja2Templates(directory="templates")
CHUNK_SIZE = 300
CHUNK_OVERLAP = 75
OPENAI_API_KEY = os.environ['OPENAI_API_KEY']
class Wiki(BaseModel):
wiki_url : str
def load_wiki_article(url: str):
try:
loader = WebBaseLoader(
web_path=url
)
docs = loader.load()
print("Wiki Loaded Successfuly")
except Exception as e:
raise Exception(e)
return docs
def wiki_text_splitter(docs):
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=CHUNK_SIZE,
chunk_overlap=CHUNK_OVERLAP)
# Make splits
splits = text_splitter.split_documents(docs)
return splits
async def create_db(splits):
chroma_instance = Chroma(persist_directory='db/')
delete_db_documents(chroma_instance)
vectorstore = Chroma.from_documents(documents=splits,
embedding=OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY),
persist_directory='db/')
#collection_metadata={"hnsw:M": 2024,"hnsw:ef": 500}
async def get_retriever():
# load chroma db
chroma_instance = Chroma(persist_directory='db/', embedding_function=OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY))
retriever = chroma_instance.as_retriever()
return retriever
def delete_db_documents(chroma_instance):
chroma_db = chromadb.PersistentClient('db/')
chroma_db.reset()
# ids = chroma_instance.get()['ids']
# if len(ids) > 0:
# print("count before", chroma_instance._collection.count())
# chroma_instance._collection.delete(ids=ids)
# print("count after", chroma_instance._collection.count())
@app.get("/", response_class=HTMLResponse)
def read_form(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/send", response_class=HTMLResponse)
async def read_wiki_url(request: Request, wiki: Wiki):
url = wiki.wiki_url
error_message = ""
try:
docs = load_wiki_article(url)
splits = wiki_text_splitter(docs)
await create_db(splits)
except Exception as e:
print(str(e))
raise Exception(str(e))
#print('Finished execution')
return templates.TemplateResponse("chat.html", {"request": request})
# try:
# # docs = load_wiki_article(url)
# # splits = wiki_text_splitter(docs)
# # await create_db(splits)
# print('Finished execution')
# #return templates.TemplateResponse("chat.html", {"request": request})
# return RedirectResponse(url="/chat")
# except Exception as e:
# rerror_message = str(e)
# print(error_message)
# return templates.TemplateResponse("index.html", {"request": request, "error_message": error_message})
@app.get("/chat", response_class=HTMLResponse)
async def chat(request: Request):
# Add any necessary context variables to the context dictionary
print("Chat endpoint reached")
context = {"request": request}
return templates.TemplateResponse("chat.html", context)
@app.post("/chat", response_class=HTMLResponse)
async def ask_respond(request: Request):
request_body = await request.json()
# Access the value of the "question" field from the request body
user_question = request_body.get("question")
retriever = await get_retriever()
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.7)
template = """Answer the question based only on the following context:
{context} and when you dont know the answer say I dont have information about AND MENTION WHAT THE USER AKED YOU ABOUT
but you can be kind for example when people are greeting you
Question: {question}
"""
# template = """Answer the question based only on the following context:
# {context}
# Refer to the {history} of the conversation -if available- to better understand the question
# Question: {question}
# """
prompt = ChatPromptTemplate.from_template(template)
rag_chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
print("human_question:", user_question)
answer = rag_chain.invoke(user_question)
print("ai_answer:", answer)
return JSONResponse(content={"answer": answer})
# def x():
# from langchain.chains import create_retrieval_chain
# from langchain.chains.combine_documents import create_stuff_documents_chain
# qa_system_prompt = """You are an assistant for question-answering tasks. \
# Use the following pieces of retrieved context to answer the question. \
# If you don't know the answer, just say that you don't know. \
# Use three sentences maximum and keep the answer concise.\
# {context}"""
# qa_prompt = ChatPromptTemplate.from_messages(
# [
# ("system", qa_system_prompt),
# MessagesPlaceholder("chat_history"),
# ("human", "{input}"),
# ]
# )
# question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
# rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
#%%
# from langchain_openai import OpenAIEmbeddings
# from langchain_community.vectorstores import Chroma
# from langchain_openai import ChatOpenAI
# from langchain.prompts import ChatPromptTemplate
# import os
# OPENAI_API_KEY = os.environ['OPENAI_API_KEY']
# # Initialize Chroma with the saved database
# chroma_instance = Chroma(persist_directory='.', embedding_function=OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY))
# # %%
# ids = chroma_instance.get()['ids']
# print("count before", chroma_instance._collection.count())
# #chroma_instance._collection.delete(ids=ids)
# print("count after", chroma_instance._collection.count())
# # %%
# import chromadb
# chroma_db = chromadb.PersistentClient('.')
# chroma_db.reset()
# chroma_db.delete_collection('langchain')
#%%
# # Prompt
# template = """Answer the question based only on the following context:
# {context} and when you dont know the answer say 'Sorry I can't answer that'
# Question: {question}
# """
# prompt = ChatPromptTemplate.from_template(template)
# prompt
# retriever = chroma_instance.as_retriever()
# llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
# from langchain_core.output_parsers import StrOutputParser
# from langchain_core.runnables import RunnablePassthrough
# rag_chain = (
# {"context": retriever, "question": RunnablePassthrough()}
# | prompt
# | llm
# | StrOutputParser()
# )
# rag_chain.invoke("who founded vodafone?")
# %%