Spaces:
Sleeping
Sleeping
Commit
·
a8b9a54
1
Parent(s):
dc8b645
oops
Browse files
app.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import List
|
3 |
+
from chainlit.types import AskFileResponse
|
4 |
+
from aimakerspace.text_utils import CharacterTextSplitter, TextFileLoader
|
5 |
+
from aimakerspace.openai_utils.prompts import (
|
6 |
+
UserRolePrompt,
|
7 |
+
SystemRolePrompt,
|
8 |
+
AssistantRolePrompt,
|
9 |
+
)
|
10 |
+
from aimakerspace.openai_utils.embedding import EmbeddingModel
|
11 |
+
from aimakerspace.vectordatabase import VectorDatabase
|
12 |
+
from aimakerspace.openai_utils.chatmodel import ChatOpenAI
|
13 |
+
import chainlit as cl
|
14 |
+
|
15 |
+
system_template = """\
|
16 |
+
Use the following context to answer a users question. If you cannot find the answer in the context, say you don't know the answer."""
|
17 |
+
system_role_prompt = SystemRolePrompt(system_template)
|
18 |
+
|
19 |
+
user_prompt_template = """\
|
20 |
+
Context:
|
21 |
+
{context}
|
22 |
+
|
23 |
+
Question:
|
24 |
+
{question}
|
25 |
+
"""
|
26 |
+
user_role_prompt = UserRolePrompt(user_prompt_template)
|
27 |
+
|
28 |
+
class RetrievalAugmentedQAPipeline:
|
29 |
+
def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:
|
30 |
+
self.llm = llm
|
31 |
+
self.vector_db_retriever = vector_db_retriever
|
32 |
+
|
33 |
+
async def arun_pipeline(self, user_query: str):
|
34 |
+
context_list = self.vector_db_retriever.search_by_text(user_query, k=4)
|
35 |
+
|
36 |
+
context_prompt = ""
|
37 |
+
for context in context_list:
|
38 |
+
context_prompt += context[0] + "\n"
|
39 |
+
|
40 |
+
formatted_system_prompt = system_role_prompt.create_message()
|
41 |
+
|
42 |
+
formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)
|
43 |
+
|
44 |
+
async def generate_response():
|
45 |
+
async for chunk in self.llm.astream([formatted_system_prompt, formatted_user_prompt]):
|
46 |
+
yield chunk
|
47 |
+
|
48 |
+
return {"response": generate_response(), "context": context_list}
|
49 |
+
|
50 |
+
text_splitter = CharacterTextSplitter()
|
51 |
+
|
52 |
+
|
53 |
+
def process_text_file(file: AskFileResponse):
|
54 |
+
import tempfile
|
55 |
+
|
56 |
+
with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") as temp_file:
|
57 |
+
temp_file_path = temp_file.name
|
58 |
+
|
59 |
+
with open(file.path, "rb") as f:
|
60 |
+
content = f.read()
|
61 |
+
|
62 |
+
with open(temp_file_path, "wb") as f:
|
63 |
+
f.write(content)
|
64 |
+
|
65 |
+
#file response no longer has a content field
|
66 |
+
|
67 |
+
text_loader = TextFileLoader(temp_file_path)
|
68 |
+
documents = text_loader.load_documents()
|
69 |
+
texts = text_splitter.split_texts(documents)
|
70 |
+
return texts
|
71 |
+
|
72 |
+
|
73 |
+
@cl.on_chat_start
|
74 |
+
async def on_chat_start():
|
75 |
+
files = None
|
76 |
+
|
77 |
+
# Wait for the user to upload a file
|
78 |
+
while files == None:
|
79 |
+
files = await cl.AskFileMessage(
|
80 |
+
content="Please upload a Text File file to begin!",
|
81 |
+
accept=["text/plain"],
|
82 |
+
max_size_mb=2,
|
83 |
+
timeout=180,
|
84 |
+
).send()
|
85 |
+
|
86 |
+
file = files[0]
|
87 |
+
|
88 |
+
msg = cl.Message(
|
89 |
+
content=f"Processing `{file.name}`..."
|
90 |
+
)
|
91 |
+
await msg.send()
|
92 |
+
|
93 |
+
# load the file
|
94 |
+
texts = process_text_file(file)
|
95 |
+
|
96 |
+
print(f"Processing {len(texts)} text chunks")
|
97 |
+
|
98 |
+
# Create a dict vector store
|
99 |
+
vector_db = VectorDatabase()
|
100 |
+
vector_db = await vector_db.abuild_from_list(texts)
|
101 |
+
|
102 |
+
chat_openai = ChatOpenAI()
|
103 |
+
|
104 |
+
# Create a chain
|
105 |
+
retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(
|
106 |
+
vector_db_retriever=vector_db,
|
107 |
+
llm=chat_openai
|
108 |
+
)
|
109 |
+
|
110 |
+
# Let the user know that the system is ready
|
111 |
+
msg.content = f"Processing `{file.name}` done. You can now ask questions!"
|
112 |
+
await msg.update()
|
113 |
+
|
114 |
+
cl.user_session.set("chain", retrieval_augmented_qa_pipeline)
|
115 |
+
|
116 |
+
|
117 |
+
@cl.on_message
|
118 |
+
async def main(message):
|
119 |
+
chain = cl.user_session.get("chain")
|
120 |
+
|
121 |
+
msg = cl.Message(content="")
|
122 |
+
result = await chain.arun_pipeline(message.content)
|
123 |
+
|
124 |
+
async for stream_resp in result["response"]:
|
125 |
+
await msg.stream_token(stream_resp)
|
126 |
+
|
127 |
+
await msg.send()
|