Files
povtornyy-ekzamen-faq-bot-c…/src/main.py
T

68 lines
1.8 KiB
Python

import os
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
from .vector_store import QdrantVectorStore
from .mcp_tool import MCPTool
app = FastAPI(
title="FAQ Bot API",
description="A simple FAQ bot using Qdrant as the vector store.",
version="1.0.0",
)
# Initialize the vector store and MCP tool
vector_store = QdrantVectorStore(
host=os.getenv("QDRANT_HOST"),
port=int(os.getenv("QDRANT_PORT", "6333")),
collection_name=os.getenv("QDRANT_COLLECTION", "faq_collection"),
)
mcp_tool = MCPTool(vector_store)
class Document(BaseModel):
id: str
text: str
metadata: dict | None = None
@app.post("/documents", status_code=201)
def add_document(doc: Document):
"""
Add a new document to the vector store.
"""
try:
vector_store.add_document(doc.id, doc.text, doc.metadata)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {"status": "added", "id": doc.id}
@app.get("/search")
def search(
query: str = Query(..., description="Search query"),
top_k: int = Query(5, ge=1, le=20, description="Number of results to return"),
):
"""
Search for documents similar to the query.
"""
try:
results = vector_store.search(query, top_k=top_k)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {"query": query, "results": results}
@app.get("/answer")
def answer(
query: str = Query(..., description="Question to answer"),
top_k: int = Query(3, ge=1, le=10, description="Number of answers to return"),
):
"""
Get the best answer(s) for the query using MCPTool.
"""
try:
answers = mcp_tool.answer(query, top_k=top_k)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {"query": query, "answers": answers}