harpreetsahota commited on
Commit
0a74a8e
1 Parent(s): fbaa379

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -100
app.py CHANGED
@@ -1,121 +1,68 @@
1
- import chainlit as cl
2
- from langchain.embeddings.openai import OpenAIEmbeddings
3
- from langchain.document_loaders.csv_loader import CSVLoader
4
- from langchain.embeddings import CacheBackedEmbeddings
5
- from langchain.text_splitter import RecursiveCharacterTextSplitter
6
- from langchain.vectorstores import FAISS
7
- from langchain.chains import RetrievalQA
8
- from langchain.chat_models import ChatOpenAI
9
- from langchain.storage import LocalFileStore
10
- from langchain.prompts.chat import (
11
- ChatPromptTemplate,
12
- SystemMessagePromptTemplate,
13
- HumanMessagePromptTemplate,
14
  )
 
15
  import chainlit as cl
16
 
17
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
18
-
19
- system_template = """
20
- Use the following pieces of context to answer the user's question.
21
-
22
- Please respond as if you were Miles Morales from the Spider-Man comics and movies. General speech patterns: Uses contractions often, like "I'm," "can't," and "don't."
23
- Might sprinkle in some Spanish, given his Puerto Rican heritage. References to modern pop culture, music, or tech. Miles is a brave young hero, grappling with his dual
24
- heritage and urban life. He has a passion for music, especially hip-hop, and is also into art, being a graffiti artist himself. He speaks with an urban and youthful tone,
25
- reflecting the voice of modern NYC youth. He might occasionally reference modern pop culture, his friends, or his school life.
26
- If you don't know the answer, just say you're unsure. Don't try to make up an answer.
27
-
28
- You can make inferences based on the context as long as it aligns with Miles' personality and experiences.
29
-
30
- Example of your interaction:
31
-
32
- User: "What did you think of the latest Spider-Man movie?"
33
- MilesBot: "Haha, watching Spider-Man on screen is always surreal for me. But it's cool to see different takes on the web-slinger's story. Always reminds me of the Spider-Verse!"
34
-
35
- Example of your response:
36
 
 
37
 
38
- ```
39
- The answer is foo
40
- ```
 
 
 
 
41
 
42
- Begin!
43
- ----------------
44
- {context}"""
45
 
46
- messages = [
47
- SystemMessagePromptTemplate.from_template(system_template),
48
- HumanMessagePromptTemplate.from_template("{question}"),
49
- ]
50
- prompt = ChatPromptTemplate(messages=messages)
51
- chain_type_kwargs = {"prompt": prompt}
52
-
53
- @cl.author_rename
54
- def rename(orig_author: str):
55
- rename_dict = {"RetrievalQA": "Crawling the Spiderverse"}
56
- return rename_dict.get(orig_author, orig_author)
57
 
58
  @cl.on_chat_start
59
- async def init():
60
- msg = cl.Message(content=f"Building Index...")
61
- await msg.send()
62
-
63
- # build FAISS index from csv
64
- loader = CSVLoader(file_path="./data/spiderverse.csv", source_column="Review_Url")
65
- data = loader.load()
66
- documents = text_splitter.transform_documents(data)
67
- store = LocalFileStore("./cache/")
68
- core_embeddings_model = OpenAIEmbeddings()
69
- embedder = CacheBackedEmbeddings.from_bytes_store(
70
- core_embeddings_model, store, namespace=core_embeddings_model.model
71
  )
72
- # make async docsearch
73
- docsearch = await cl.make_async(FAISS.from_documents)(documents, embedder)
74
-
75
- chain = RetrievalQA.from_chain_type(
76
- ChatOpenAI(model="gpt-4", temperature=0, streaming=True),
77
- chain_type="stuff",
78
- return_source_documents=True,
79
- retriever=docsearch.as_retriever(),
80
- chain_type_kwargs = {"prompt": prompt}
81
  )
82
 
83
- msg.content = f"Index built!"
84
- await msg.send()
 
 
85
 
86
- cl.user_session.set("chain", chain)
87
 
88
 
89
  @cl.on_message
90
  async def main(message):
91
- chain = cl.user_session.get("chain")
92
- cb = cl.AsyncLangchainCallbackHandler(
93
- stream_final_answer=False, answer_prefix_tokens=["FINAL", "ANSWER"]
94
- )
95
- cb.answer_reached = True
96
- res = await chain.acall(message, callbacks=[cb], )
97
-
98
- answer = res["result"]
99
- source_elements = []
100
- visited_sources = set()
101
 
102
- # Get the documents from the user session
103
- docs = res["source_documents"]
104
- metadatas = [doc.metadata for doc in docs]
105
- all_sources = [m["source"] for m in metadatas]
106
 
107
- for source in all_sources:
108
- if source in visited_sources:
109
- continue
110
- visited_sources.add(source)
111
- # Create the text element referenced in the message
112
- source_elements.append(
113
- cl.Text(content="https://www.imdb.com" + source, name="Review URL")
114
- )
115
 
116
- if source_elements:
117
- answer += f"\nSources: {', '.join([e.content.decode('utf-8') for e in source_elements])}"
118
- else:
119
- answer += "\nNo sources found"
120
 
121
- await cl.Message(content=answer, elements=source_elements).send()
 
1
+ import os
2
+ import openai
3
+
4
+ from llama_index.query_engine.retriever_query_engine import RetrieverQueryEngine
5
+ from llama_index.callbacks.base import CallbackManager
6
+ from llama_index import (
7
+ LLMPredictor,
8
+ ServiceContext,
9
+ StorageContext,
10
+ load_index_from_storage,
 
 
 
11
  )
12
+ from llama_index.llms import OpenAI
13
  import chainlit as cl
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ openai.api_key = os.environ.get("OPENAI_API_KEY")
17
 
18
+ try:
19
+ # rebuild storage context
20
+ storage_context = StorageContext.from_defaults(persist_dir="./storage")
21
+ # load index
22
+ index = load_index_from_storage(storage_context)
23
+ except:
24
+ from llama_index import GPTVectorStoreIndex, SimpleDirectoryReader
25
 
26
+ documents = SimpleDirectoryReader(input_files=["hitchhikers.pdf"]).load_data()
27
+ index = GPTVectorStoreIndex.from_documents(documents)
28
+ index.storage_context.persist()
29
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  @cl.on_chat_start
32
+ async def factory():
33
+ llm_predictor = LLMPredictor(
34
+ llm=OpenAI(
35
+ temperature=0,
36
+ model="ft:gpt-3.5-turbo-0613:personal::7ru6l1bi",
37
+ streaming=True,
38
+ context_window=2048,
39
+ ),
 
 
 
 
40
  )
41
+ service_context = ServiceContext.from_defaults(
42
+ llm_predictor=llm_predictor,
43
+ chunk_size=512,
44
+ callback_manager=CallbackManager([cl.LlamaIndexCallbackHandler()]),
 
 
 
 
 
45
  )
46
 
47
+ query_engine = index.as_query_engine(
48
+ service_context=service_context,
49
+ streaming=True,
50
+ )
51
 
52
+ cl.user_session.set("query_engine", query_engine)
53
 
54
 
55
  @cl.on_message
56
  async def main(message):
57
+ query_engine = cl.user_session.get("query_engine") # type: RetrieverQueryEngine
58
+ response = await cl.make_async(query_engine.query)(message)
 
 
 
 
 
 
 
 
59
 
60
+ response_message = cl.Message(content="")
 
 
 
61
 
62
+ for token in response.response_gen:
63
+ await response_message.stream_token(token=token)
 
 
 
 
 
 
64
 
65
+ if response.response_txt:
66
+ response_message.content = response.response_txt
 
 
67
 
68
+ await response_message.send()