-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
217 lines (178 loc) · 6.69 KB
/
Copy pathapp.py
File metadata and controls
217 lines (178 loc) · 6.69 KB
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
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
import os
from dotenv import load_dotenv
from typing import List, Optional
import json
# Load environment variables
load_dotenv()
# Initialize FastAPI app
app = FastAPI(title="EY Research Assistant API")
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def root():
return {"message": "Welcome to EY Research Assistant API"}
@app.get("/health")
async def health_check():
return {"status": "healthy"}
import shutil
from utils.document_processor import process_document
from utils.vector_store import VectorStore
from utils.ai_service import AIService
from utils.database import Database
import uuid
import datetime
# Initialize services
try:
vector_store = VectorStore()
ai_service = AIService()
db = Database()
except Exception as e:
print(f"Error initializing services: {e}")
@app.post("/upload-document")
async def upload_document(
file: UploadFile = File(...),
user_id: str = Form(None),
document_type: str = Form(None)
):
try:
# Create a unique ID for the document
document_id = str(uuid.uuid4())
# Save the file to disk
file_location = f"uploads/{document_id}_{file.filename}"
with open(file_location, "wb") as file_object:
shutil.copyfileobj(file.file, file_object)
# Process the document to extract text
document_text = process_document(file_location)
if not document_text:
return JSONResponse(
status_code=400,
content={"detail": "Could not extract text from document"}
)
# Split the text into chunks
chunks = ai_service.text_splitter.split_text(document_text)
# Get embeddings for chunks
embeddings = ai_service.get_embeddings(chunks)
# Prepare vectors for Pinecone
vectors = []
for i, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
vectors.append({
"id": f"{document_id}_{i}",
"values": embedding,
"metadata": {
"document_id": document_id,
"chunk_index": i,
"text": chunk,
"source": file.filename
}
})
# Upsert vectors to Pinecone
vector_store.upsert_vectors(vectors)
# Store document metadata in Supabase
document_data = {
"id": document_id,
"filename": file.filename,
"user_id": user_id,
"document_type": document_type,
"upload_date": datetime.datetime.now().isoformat(),
"chunk_count": len(chunks)
}
db.insert_document(document_data)
return {
"document_id": document_id,
"filename": file.filename,
"chunk_count": len(chunks),
"message": "Document processed successfully"
}
except Exception as e:
return JSONResponse(
status_code=500,
content={"detail": f"Error processing document: {str(e)}"}
)
@app.post("/query")
async def query(
question: str = Form(...),
user_id: str = Form(None),
model: str = Form("gpt-4") # Options: gpt-4, claude
):
try:
# Store query in database
query_data = {
"id": str(uuid.uuid4()),
"user_id": user_id,
"question": question,
"model": model,
"created_at": datetime.datetime.now().isoformat()
}
db.insert_query(query_data)
# Generate embedding for the question
question_embedding = ai_service.get_embeddings([question])[0]
# Query Pinecone for relevant chunks
query_response = vector_store.query(question_embedding)
if not query_response.matches:
return {"answer": "I couldn't find relevant information to answer your question."}
# Extract the text from the matched chunks
context = "\n\n".join([match.metadata["text"] for match in query_response.matches])
# Generate the answer based on the model choice
if model == "claude" and ai_service.anthropic_client:
prompt = f"""
Question: {question}
Context information:
{context}
Please answer the question based only on the provided context. If the answer cannot be determined from the context, say so.
"""
answer = ai_service.query_anthropic(prompt)
else:
# Use OpenAI via langchain
prompt = f"""
Answer the following question based on the context provided. If the answer cannot be determined from the context, say so.
Question: {question}
Context:
{context}
"""
answer = ai_service.openai_llm.predict(prompt)
# Update query with the answer
db.supabase.table("queries").update({"answer": answer}).eq("id", query_data["id"]).execute()
return {
"query_id": query_data["id"],
"answer": answer,
"sources": [{"document": match.metadata["source"], "relevance": match.score} for match in query_response.matches[:3]]
}
except Exception as e:
return JSONResponse(
status_code=500,
content={"detail": f"Error processing query: {str(e)}"}
)
@app.get("/documents")
async def get_documents(user_id: Optional[str] = None):
"""Get all documents, optionally filtered by user_id."""
try:
response = db.get_documents(user_id)
return {"documents": response.data}
except Exception as e:
return JSONResponse(
status_code=500,
content={"detail": f"Error getting documents: {str(e)}"}
)
@app.get("/queries")
async def get_queries(user_id: Optional[str] = None, limit: int = 10):
"""Get recent queries, optionally filtered by user_id."""
try:
response = db.get_queries(user_id, limit)
return {"queries": response.data}
except Exception as e:
return JSONResponse(
status_code=500,
content={"detail": f"Error getting queries: {str(e)}"}
)
if __name__ == "__main__":
uvicorn.run("app:app", host="0.0.0.0", port=8080, reload=True)