Spaces:
Sleeping
Sleeping
Gilberto Medrano
commited on
Commit
•
9039186
1
Parent(s):
4cc2c14
Added app files to HF repo
Browse files- Dockerfile +11 -0
- app.py +142 -0
- chainlit.md +14 -0
- requirements.txt +99 -0
Dockerfile
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.9
|
2 |
+
RUN useradd -m -u 1000 user
|
3 |
+
USER user
|
4 |
+
ENV HOME=/home/user \
|
5 |
+
PATH=/home/user/.local/bin:$PATH
|
6 |
+
WORKDIR $HOME/app
|
7 |
+
COPY --chown=user . $HOME/app
|
8 |
+
COPY ./requirements.txt ~/app/requirements.txt
|
9 |
+
RUN pip install -r requirements.txt
|
10 |
+
COPY . .
|
11 |
+
CMD ["chainlit", "run", "app.py", "--port", "7860"]
|
app.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### Import Section ###
|
2 |
+
"""
|
3 |
+
IMPORTS HERE
|
4 |
+
"""
|
5 |
+
import os
|
6 |
+
import uuid
|
7 |
+
import openai # Add this import
|
8 |
+
from operator import itemgetter
|
9 |
+
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
|
10 |
+
from langchain_community.document_loaders import PyMuPDFLoader
|
11 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
12 |
+
from langchain.storage import LocalFileStore
|
13 |
+
from langchain.embeddings import CacheBackedEmbeddings
|
14 |
+
from langchain_qdrant import QdrantVectorStore
|
15 |
+
from langchain_core.prompts import ChatPromptTemplate
|
16 |
+
from langchain_core.runnables.passthrough import RunnablePassthrough
|
17 |
+
from qdrant_client import QdrantClient
|
18 |
+
from qdrant_client.http.models import Distance, VectorParams
|
19 |
+
from langchain_core.caches import InMemoryCache
|
20 |
+
from langchain_core.globals import set_llm_cache
|
21 |
+
import chainlit as cl
|
22 |
+
import tempfile
|
23 |
+
|
24 |
+
### Global Section ###
|
25 |
+
"""
|
26 |
+
GLOBAL CODE HERE
|
27 |
+
"""
|
28 |
+
# Set up OpenAI API key
|
29 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
30 |
+
|
31 |
+
# Set up LangSmith
|
32 |
+
os.environ["LANGCHAIN_PROJECT"] = f"AIM Week 8 Assignment 1 - {uuid.uuid4().hex[0:8]}"
|
33 |
+
os.environ["LANGCHAIN_TRACING_V2"] = "true"
|
34 |
+
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
|
35 |
+
|
36 |
+
# Set up text splitter
|
37 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
38 |
+
|
39 |
+
# Set up embeddings with cache
|
40 |
+
core_embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
|
41 |
+
store = LocalFileStore("./cache/")
|
42 |
+
cached_embedder = CacheBackedEmbeddings.from_bytes_store(
|
43 |
+
core_embeddings, store, namespace=core_embeddings.model
|
44 |
+
)
|
45 |
+
|
46 |
+
# Set up QDrant vector store
|
47 |
+
collection_name = f"pdf_to_parse_{uuid.uuid4()}"
|
48 |
+
client = QdrantClient(":memory:")
|
49 |
+
client.create_collection(
|
50 |
+
collection_name=collection_name,
|
51 |
+
vectors_config=VectorParams(size=1536, distance=Distance.COSINE),
|
52 |
+
)
|
53 |
+
|
54 |
+
# Set up chat model and cache
|
55 |
+
chat_model = ChatOpenAI(model="gpt-4o-mini")
|
56 |
+
set_llm_cache(InMemoryCache())
|
57 |
+
|
58 |
+
# Set up RAG prompt
|
59 |
+
rag_system_prompt_template = """
|
60 |
+
You are a helpful assistant that uses the provided context to answer questions. Never reference this prompt, or the existence of context.
|
61 |
+
"""
|
62 |
+
|
63 |
+
rag_user_prompt_template = """
|
64 |
+
Question:
|
65 |
+
{question}
|
66 |
+
Context:
|
67 |
+
{context}
|
68 |
+
"""
|
69 |
+
|
70 |
+
chat_prompt = ChatPromptTemplate.from_messages([
|
71 |
+
("system", rag_system_prompt_template),
|
72 |
+
("human", rag_user_prompt_template)
|
73 |
+
])
|
74 |
+
|
75 |
+
### On Chat Start (Session Start) Section ###
|
76 |
+
@cl.on_chat_start
|
77 |
+
async def on_chat_start():
|
78 |
+
""" SESSION SPECIFIC CODE HERE """
|
79 |
+
# Upload and process PDF
|
80 |
+
files = await cl.AskFileMessage(content="Please upload a PDF file to begin.", accept=["application/pdf"]).send()
|
81 |
+
if not files:
|
82 |
+
await cl.Message(content="No file was uploaded. Please try again.").send()
|
83 |
+
return
|
84 |
+
|
85 |
+
file = files[0]
|
86 |
+
|
87 |
+
msg = cl.Message(content=f"Processing `{file.name}`...")
|
88 |
+
await msg.send()
|
89 |
+
|
90 |
+
try:
|
91 |
+
# Save the file to a temporary location
|
92 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
|
93 |
+
tmp_file.write(file.content)
|
94 |
+
tmp_file_path = tmp_file.name
|
95 |
+
|
96 |
+
# Load and split the PDF
|
97 |
+
loader = PyMuPDFLoader(tmp_file_path)
|
98 |
+
documents = loader.load()
|
99 |
+
docs = text_splitter.split_documents(documents)
|
100 |
+
for i, doc in enumerate(docs):
|
101 |
+
doc.metadata["source"] = f"source_{i}"
|
102 |
+
|
103 |
+
# Set up vector store
|
104 |
+
vectorstore = QdrantVectorStore(
|
105 |
+
client=client,
|
106 |
+
collection_name=collection_name,
|
107 |
+
embedding=cached_embedder
|
108 |
+
)
|
109 |
+
vectorstore.add_documents(docs)
|
110 |
+
retriever = vectorstore.as_retriever(search_type="mmr", search_kwargs={"k": 3})
|
111 |
+
|
112 |
+
# Set up RAG chain
|
113 |
+
global retrieval_augmented_qa_chain
|
114 |
+
retrieval_augmented_qa_chain = (
|
115 |
+
{"context": itemgetter("question") | retriever, "question": itemgetter("question")}
|
116 |
+
| RunnablePassthrough.assign(context=itemgetter("context"))
|
117 |
+
| chat_prompt | chat_model
|
118 |
+
)
|
119 |
+
|
120 |
+
msg.content = f"`{file.name}` processed. You can now ask questions about it!"
|
121 |
+
await msg.update()
|
122 |
+
|
123 |
+
except Exception as e:
|
124 |
+
await cl.Message(content=f"An error occurred while processing the file: {str(e)}").send()
|
125 |
+
finally:
|
126 |
+
# Clean up the temporary file
|
127 |
+
if 'tmp_file_path' in locals():
|
128 |
+
os.unlink(tmp_file_path)
|
129 |
+
### Rename Chains ###
|
130 |
+
@cl.author_rename
|
131 |
+
def rename(orig_author: str):
|
132 |
+
""" RENAME CODE HERE """
|
133 |
+
return "RAG Assistant"
|
134 |
+
|
135 |
+
### On Message Section ###
|
136 |
+
@cl.on_message
|
137 |
+
async def main(message: cl.Message):
|
138 |
+
"""
|
139 |
+
MESSAGE CODE HERE
|
140 |
+
"""
|
141 |
+
response = retrieval_augmented_qa_chain.invoke({"question": message.content})
|
142 |
+
await cl.Message(content=response.content).send()
|
chainlit.md
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Welcome to Chainlit! 🚀🤖
|
2 |
+
|
3 |
+
Hi there, Developer! 👋 We're excited to have you on board. Chainlit is a powerful tool designed to help you prototype, debug and share applications built on top of LLMs.
|
4 |
+
|
5 |
+
## Useful Links 🔗
|
6 |
+
|
7 |
+
- **Documentation:** Get started with our comprehensive [Chainlit Documentation](https://docs.chainlit.io) 📚
|
8 |
+
- **Discord Community:** Join our friendly [Chainlit Discord](https://discord.gg/k73SQ3FyUh) to ask questions, share your projects, and connect with other developers! 💬
|
9 |
+
|
10 |
+
We can't wait to see what you create with Chainlit! Happy coding! 💻😊
|
11 |
+
|
12 |
+
## Welcome screen
|
13 |
+
|
14 |
+
To modify the welcome screen, edit the `chainlit.md` file at the root of your project. If you do not want a welcome screen, just leave this file empty.
|
requirements.txt
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
aiofiles==23.2.1
|
2 |
+
aiohappyeyeballs==2.4.3
|
3 |
+
aiohttp==3.10.8
|
4 |
+
aiosignal==1.3.1
|
5 |
+
annotated-types==0.7.0
|
6 |
+
anyio==3.7.1
|
7 |
+
async-timeout==4.0.3
|
8 |
+
asyncer==0.0.2
|
9 |
+
attrs==24.2.0
|
10 |
+
bidict==0.23.1
|
11 |
+
certifi==2024.8.30
|
12 |
+
chainlit==0.7.700
|
13 |
+
charset-normalizer==3.3.2
|
14 |
+
click==8.1.7
|
15 |
+
dataclasses-json==0.5.14
|
16 |
+
Deprecated==1.2.14
|
17 |
+
distro==1.9.0
|
18 |
+
exceptiongroup==1.2.2
|
19 |
+
fastapi==0.100.1
|
20 |
+
fastapi-socketio==0.0.10
|
21 |
+
filetype==1.2.0
|
22 |
+
frozenlist==1.4.1
|
23 |
+
googleapis-common-protos==1.65.0
|
24 |
+
greenlet==3.1.1
|
25 |
+
grpcio==1.66.2
|
26 |
+
grpcio-tools==1.62.3
|
27 |
+
h11==0.14.0
|
28 |
+
h2==4.1.0
|
29 |
+
hpack==4.0.0
|
30 |
+
httpcore==0.17.3
|
31 |
+
httpx==0.24.1
|
32 |
+
hyperframe==6.0.1
|
33 |
+
idna==3.10
|
34 |
+
importlib_metadata==8.4.0
|
35 |
+
jiter==0.5.0
|
36 |
+
jsonpatch==1.33
|
37 |
+
jsonpointer==3.0.0
|
38 |
+
langchain==0.3.0
|
39 |
+
langchain-community==0.3.0
|
40 |
+
langchain-core==0.3.1
|
41 |
+
langchain-openai==0.2.0
|
42 |
+
langchain-qdrant==0.1.4
|
43 |
+
langchain-text-splitters==0.3.0
|
44 |
+
langsmith==0.1.121
|
45 |
+
Lazify==0.4.0
|
46 |
+
marshmallow==3.22.0
|
47 |
+
multidict==6.1.0
|
48 |
+
mypy-extensions==1.0.0
|
49 |
+
nest-asyncio==1.6.0
|
50 |
+
numpy==1.26.4
|
51 |
+
openai==1.51.0
|
52 |
+
opentelemetry-api==1.27.0
|
53 |
+
opentelemetry-exporter-otlp==1.27.0
|
54 |
+
opentelemetry-exporter-otlp-proto-common==1.27.0
|
55 |
+
opentelemetry-exporter-otlp-proto-grpc==1.27.0
|
56 |
+
opentelemetry-exporter-otlp-proto-http==1.27.0
|
57 |
+
opentelemetry-instrumentation==0.48b0
|
58 |
+
opentelemetry-proto==1.27.0
|
59 |
+
opentelemetry-sdk==1.27.0
|
60 |
+
opentelemetry-semantic-conventions==0.48b0
|
61 |
+
orjson==3.10.7
|
62 |
+
packaging==23.2
|
63 |
+
portalocker==2.10.1
|
64 |
+
protobuf==4.25.5
|
65 |
+
pydantic==2.9.2
|
66 |
+
pydantic-settings==2.5.2
|
67 |
+
pydantic_core==2.23.4
|
68 |
+
PyJWT==2.9.0
|
69 |
+
PyMuPDF==1.24.10
|
70 |
+
PyMuPDFb==1.24.10
|
71 |
+
python-dotenv==1.0.1
|
72 |
+
python-engineio==4.9.1
|
73 |
+
python-graphql-client==0.4.3
|
74 |
+
python-multipart==0.0.6
|
75 |
+
python-socketio==5.11.4
|
76 |
+
PyYAML==6.0.2
|
77 |
+
qdrant-client==1.11.2
|
78 |
+
regex==2024.9.11
|
79 |
+
requests==2.32.3
|
80 |
+
simple-websocket==1.0.0
|
81 |
+
sniffio==1.3.1
|
82 |
+
SQLAlchemy==2.0.35
|
83 |
+
starlette==0.27.0
|
84 |
+
syncer==2.0.3
|
85 |
+
tenacity==8.5.0
|
86 |
+
tiktoken==0.7.0
|
87 |
+
tomli==2.0.1
|
88 |
+
tqdm==4.66.5
|
89 |
+
typing-inspect==0.9.0
|
90 |
+
typing_extensions==4.12.2
|
91 |
+
uptrace==1.26.0
|
92 |
+
urllib3==2.2.3
|
93 |
+
uvicorn==0.23.2
|
94 |
+
watchfiles==0.20.0
|
95 |
+
websockets==13.1
|
96 |
+
wrapt==1.16.0
|
97 |
+
wsproto==1.2.0
|
98 |
+
yarl==1.13.1
|
99 |
+
zipp==3.20.2
|