Delete main.py
Browse files
main.py
DELETED
@@ -1,82 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import json
|
3 |
-
import asyncio
|
4 |
-
from typing import AsyncGenerator
|
5 |
-
|
6 |
-
from fastapi.middleware.cors import CORSMiddleware
|
7 |
-
from fastapi.responses import StreamingResponse
|
8 |
-
from fastapi import FastAPI, HTTPException
|
9 |
-
|
10 |
-
from websearch import QueryRequest, PerplexityClient, parse_perplexity_response
|
11 |
-
|
12 |
-
# load .env file
|
13 |
-
from dotenv import load_dotenv
|
14 |
-
load_dotenv()
|
15 |
-
|
16 |
-
# Initialize FastAPI app
|
17 |
-
app = FastAPI()
|
18 |
-
|
19 |
-
# Add CORS middleware to allow frontend connections
|
20 |
-
app.add_middleware(
|
21 |
-
CORSMiddleware,
|
22 |
-
allow_origins=["*"], # Adjust this in production
|
23 |
-
allow_credentials=True,
|
24 |
-
allow_methods=["*"],
|
25 |
-
allow_headers=["*"],
|
26 |
-
)
|
27 |
-
|
28 |
-
# Initialize Perplexity client
|
29 |
-
perplexity_client = PerplexityClient(
|
30 |
-
api_key=os.environ["PERPLEXITY_AUTH_TOKEN"]
|
31 |
-
)
|
32 |
-
|
33 |
-
|
34 |
-
async def generate_stream(query: str) -> AsyncGenerator[str, None]:
|
35 |
-
"""
|
36 |
-
Async generator to stream JSON response
|
37 |
-
|
38 |
-
Args:
|
39 |
-
query (str): User query
|
40 |
-
|
41 |
-
Yields:
|
42 |
-
str: JSON-encoded chunks of response
|
43 |
-
"""
|
44 |
-
try:
|
45 |
-
# Fetch response from Perplexity
|
46 |
-
response = await perplexity_client.generate_response(query)
|
47 |
-
|
48 |
-
# Parse the response
|
49 |
-
parsed_response = parse_perplexity_response(response)
|
50 |
-
|
51 |
-
# Stream the parsed response as JSON chunks
|
52 |
-
yield json.dumps(parsed_response)
|
53 |
-
|
54 |
-
except Exception as e:
|
55 |
-
yield json.dumps({"error": str(e)})
|
56 |
-
|
57 |
-
|
58 |
-
@app.post("/websearch")
|
59 |
-
async def handle_query(request: QueryRequest):
|
60 |
-
"""
|
61 |
-
Endpoint to handle user queries and stream responses
|
62 |
-
|
63 |
-
Args:
|
64 |
-
request (QueryRequest): Query request model
|
65 |
-
|
66 |
-
Returns:
|
67 |
-
StreamingResponse: Streaming JSON response
|
68 |
-
"""
|
69 |
-
return StreamingResponse(
|
70 |
-
generate_stream(request.query),
|
71 |
-
media_type="application/json"
|
72 |
-
)
|
73 |
-
|
74 |
-
|
75 |
-
# Optional: Health check endpoint
|
76 |
-
@app.get("/health")
|
77 |
-
async def health_check():
|
78 |
-
return {"status": "healthy"}
|
79 |
-
|
80 |
-
# Run the app with:
|
81 |
-
# uvicorn main:app --reload
|
82 |
-
# Make sure to set PERPLEXITY_API_KEY environment variable
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|