-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastapi_server.py
More file actions
141 lines (122 loc) · 4.27 KB
/
fastapi_server.py
File metadata and controls
141 lines (122 loc) · 4.27 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
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional
from fastapi.middleware.cors import CORSMiddleware
import os
import requests
import logging
import pandas as pd
from chatbot_core import chatbot
# Logging setup
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI()
# CORS setup
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # for development; restrict in prod
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Pydantic models
class ChatRequest(BaseModel):
pdf_urls: List[str]
question: str
conversation_id: Optional[str] = "default"
class AnswerRequest(BaseModel):
question: str
answer: str
conversation_id: Optional[str] = "default"
timestamp: Optional[str] = None
@app.post("/chat")
async def chat_endpoint(request: ChatRequest):
logger.info(f"Chat request received: {request.question}")
try:
# Use your existing RAG system!
response = chatbot.ask_question(request.question, request.conversation_id)
# Forward answer to /answers
try:
requests.post(
"http://localhost:8000/answers",
json={
"conversation_id": request.conversation_id,
"question": request.question,
"answer": response["answer"]
}
)
except Exception as e:
logger.warning(f"Could not forward to /answers: {e}")
return {"answer": response["answer"]}
except Exception as e:
logger.error(f"Error processing question: {e}")
return {"error": str(e)}
# Store answers in memory
stored_answers = []
# Modify your existing receive_answer function:
@app.post("/answer")
async def receive_answer(request: AnswerRequest):
"""Receive and process answers from Streamlit"""
try:
logger.info(f"Received answer for question: '{request.question[:50]}...'")
logger.info(f"Answer length: {len(request.answer)} characters")
logger.info(f"Conversation ID: {request.conversation_id}")
# Store the answer for browser viewing
answer_data = {
"question": request.question,
"answer": request.answer,
"conversation_id": request.conversation_id,
"timestamp": request.timestamp,
"received_at": str(pd.Timestamp.now()) if 'pd' in globals() else "now"
}
stored_answers.append(answer_data)
response_data = {
"status": "success",
"message": "Answer received and stored successfully",
"question": request.question,
"answer_length": len(request.answer),
"conversation_id": request.conversation_id,
"timestamp": request.timestamp,
"total_stored": len(stored_answers)
}
return response_data
except Exception as e:
logger.error(f"Error processing answer: {e}")
return {"status": "error", "message": str(e)}
# Add new endpoints for browser viewing:
@app.get("/answers/all")
async def get_all_answers():
"""View all stored answers in browser"""
return {
"total_answers": len(stored_answers),
"answers": stored_answers
}
@app.get("/answers/latest")
async def get_latest_answer():
"""View the most recent answer"""
if stored_answers:
return {
"latest_answer": stored_answers[-1],
"total_answers": len(stored_answers)
}
else:
return {"message": "No answers stored yet"}
@app.get("/")
async def root():
"""Root endpoint with navigation"""
return {
"message": "PDF Chatbot API",
"endpoints": {
"chat": "POST /chat - Process PDFs and ask questions",
"answer": "POST /answer - Receive answers from Streamlit",
"view_all_answers": "GET /answers/all - View all stored answers",
"view_latest": "GET /answers/latest - View latest answer"
}
}
# The Connection:
# /answer (POST) → Writes to stored_answers
# /answers/latest (GET) → Reads from stored_answers
# /answers/all (GET) → Reads from stored_answers
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)