thomasjacob04 commited on
Commit
d228ce2
·
verified ·
1 Parent(s): 8f07e06

Create realapp.py

Browse files
Files changed (1) hide show
  1. realapp.py +96 -0
realapp.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Iterable
3
+ from tempfile import TemporaryDirectory
4
+ from dotenv import load_dotenv
5
+
6
+ from docling import DoclingPDFLoader
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain_huggingface.embeddings import HuggingFaceEmbeddings
9
+ from langchain_milvus import Milvus
10
+ from langchain_huggingface import HuggingFaceEndpoint
11
+ from langchain_core.documents import Document as LCDocument
12
+ from langchain_core.output_parsers import StrOutputParser
13
+ from langchain_core.prompts import PromptTemplate
14
+ from langchain_core.runnables import RunnablePassthrough
15
+ from fastapi import FastAPI, HTTPException
16
+ from pydantic import BaseModel
17
+
18
+ # Load environment variables
19
+ load_dotenv()
20
+
21
+ # File paths configuration
22
+ FILE_PATHS = ["vol1.pdf", "vol2.pdf", "vol3.pdf"]
23
+
24
+ # Load and split documents
25
+ loader = DoclingPDFLoader(file_paths=FILE_PATHS)
26
+ docs = loader.load()
27
+
28
+ text_splitter = RecursiveCharacterTextSplitter(
29
+ chunk_size=1000,
30
+ chunk_overlap=200,
31
+ )
32
+ splits = text_splitter.split_documents(docs)
33
+
34
+ # Set up embeddings
35
+ HF_EMBED_MODEL_ID = "BAAI/bge-small-en-v1.5"
36
+ embeddings = HuggingFaceEmbeddings(model_name=HF_EMBED_MODEL_ID)
37
+
38
+ # Configure Milvus
39
+ MILVUS_URI = os.environ.get(
40
+ "MILVUS_URI", f"{(tmp_dir := TemporaryDirectory()).name}/milvus_demo.db"
41
+ )
42
+
43
+ # Initialize vector store
44
+ vectorstore = Milvus.from_documents(
45
+ splits,
46
+ embeddings,
47
+ connection_args={"uri": MILVUS_URI},
48
+ drop_old=True,
49
+ index_params={
50
+ "index_type": "IVF_FLAT",
51
+ "metric_type": "L2",
52
+ "params": {"nlist": 100}
53
+ },
54
+ )
55
+
56
+ # Set up LLM
57
+ HF_API_KEY = os.environ.get("HF_TOKEN")
58
+ HF_LLM_MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.3"
59
+ llm = HuggingFaceEndpoint(
60
+ repo_id=HF_LLM_MODEL_ID,
61
+ huggingfacehub_api_token=HF_API_KEY,
62
+ )
63
+
64
+ # FastAPI setup
65
+ app = FastAPI()
66
+
67
+ class QueryRequest(BaseModel):
68
+ question: str
69
+
70
+ def format_docs(docs: Iterable[LCDocument]):
71
+ return "\n\n".join(doc.page_content for doc in docs)
72
+
73
+ # Create RAG chain
74
+ retriever = vectorstore.as_retriever()
75
+ prompt = PromptTemplate.from_template(
76
+ "Context information is below.\n---------------------\n{context}\n---------------------\nGiven the context information and not prior knowledge, answer the query.\nQuery: {question}\nAnswer:\n"
77
+ )
78
+
79
+ rag_chain = (
80
+ {"context": retriever | format_docs, "question": RunnablePassthrough()}
81
+ | prompt
82
+ | llm
83
+ | StrOutputParser()
84
+ )
85
+
86
+ @app.post("/query")
87
+ async def query_documents(request: QueryRequest):
88
+ try:
89
+ response = rag_chain.invoke(request.question)
90
+ return {"answer": response}
91
+ except Exception as e:
92
+ raise HTTPException(status_code=500, detail=str(e))
93
+
94
+ if __name__ == "__main__":
95
+ import uvicorn
96
+ uvicorn.run(app, host="0.0.0.0", port=8000)