Spaces:
Sleeping
Sleeping
File size: 2,244 Bytes
bec97ef a3421c9 bec97ef eddd367 bec97ef cc81b05 bec97ef cc81b05 bec97ef cc81b05 bec97ef cc81b05 bec97ef cc81b05 bec97ef cc81b05 bec97ef cc81b05 bec97ef eddd367 bec97ef cc81b05 | 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 | # FastAPI entrypoint for AskRoss chatbot backend
import os
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from dotenv import load_dotenv
import asyncio
# Load environment variables
load_dotenv()
from askross_agent import askross_agent
from session import get_session
app = FastAPI()
# FIX: Define the absolute path to the 'static' folder in your root directory
base_dir = os.path.dirname(os.path.abspath(__file__))
static_dir = os.path.join(base_dir, "static")
# Mount the static directory
# This allows access via /static/filename.js
app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static")
@app.get("/", response_class=HTMLResponse)
def root():
# Serve index.html from the static folder
index_path = os.path.join(static_dir, "index.html")
with open(index_path, "r", encoding="utf-8") as f:
return f.read()
@app.get("/widget.js")
def widget_js():
# Serve chatbot.js from the static folder
js_path = os.path.join(static_dir, "chatbot.js")
return FileResponse(js_path, media_type="application/javascript")
@app.get("/widget.css")
def widget_css():
# Serve style.css from the static folder
css_path = os.path.join(static_dir, "style.css")
return FileResponse(css_path, media_type="text/css")
@app.post("/chat")
async def chat_endpoint(request: Request):
data = await request.json()
user_message = data.get("message")
thread_id = data.get("thread_id")
page_id = data.get("page_id", "home")
page_title = data.get("page_title", "AskRoss")
if not user_message or not thread_id:
return JSONResponse({"error": "Missing message or thread_id"}, status_code=400)
session = get_session(thread_id)
# Run agent asynchronously
try:
from agents import Runner
prompt = f"[page_id={page_id}] [page_title={page_title}] {user_message}"
result = await Runner.run(
askross_agent,
prompt,
session=session
)
return {"message": result.final_output, "thread_id": thread_id}
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500) |