Skip to content

Add timeout and error handling in FastAPI uvicorn server #2044

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions examples/high_level_api/fastapi_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,24 @@
To actually see the implementation of the server, see llama_cpp/server/app.py

"""

import os
import uvicorn

from llama_cpp.server.app import create_app
import asyncio

if __name__ == "__main__":
app = create_app()

uvicorn.run(
app, host=os.getenv("HOST", "localhost"), port=int(os.getenv("PORT", 8000))
)
try:
# Run the server with timeout config (graceful shutdown handling)
uvicorn.run(
app,
host=os.getenv("HOST", "localhost"),
port=int(os.getenv("PORT", 8000)),
timeout_keep_alive=10, # Optional: disconnect inactive clients after 10s
timeout_notify=5 # Optional: timeout for graceful shutdown notification
)
except asyncio.TimeoutError:
print("⏰ Server startup timed out.")
except Exception as e:
print(f"🚨 An unexpected error occurred: {e}")