__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import base64
  2. import os
  3. import random
  4. from pathlib import Path
  5. import typer
  6. import uvicorn
  7. from open_webui.env import GLOBAL_LOG_LEVEL
  8. app = typer.Typer()
  9. KEY_FILE = Path.cwd() / ".webui_secret_key"
  10. @app.command()
  11. def serve(
  12. host: str = "0.0.0.0",
  13. port: int = 8080,
  14. ):
  15. os.environ["FROM_INIT_PY"] = "true"
  16. if os.getenv("WEBUI_SECRET_KEY") is None:
  17. typer.echo(
  18. "Loading WEBUI_SECRET_KEY from file, not provided as an environment variable."
  19. )
  20. if not KEY_FILE.exists():
  21. typer.echo(f"Generating a new secret key and saving it to {KEY_FILE}")
  22. KEY_FILE.write_bytes(base64.b64encode(random.randbytes(12)))
  23. typer.echo(f"Loading WEBUI_SECRET_KEY from {KEY_FILE}")
  24. os.environ["WEBUI_SECRET_KEY"] = KEY_FILE.read_text()
  25. if os.getenv("USE_CUDA_DOCKER", "false") == "true":
  26. typer.echo(
  27. "CUDA is enabled, appending LD_LIBRARY_PATH to include torch/cudnn & cublas libraries."
  28. )
  29. LD_LIBRARY_PATH = os.getenv("LD_LIBRARY_PATH", "").split(":")
  30. os.environ["LD_LIBRARY_PATH"] = ":".join(
  31. LD_LIBRARY_PATH
  32. + [
  33. "/usr/local/lib/python3.11/site-packages/torch/lib",
  34. "/usr/local/lib/python3.11/site-packages/nvidia/cudnn/lib",
  35. ]
  36. )
  37. try:
  38. import torch
  39. assert torch.cuda.is_available(), "CUDA not available"
  40. typer.echo("CUDA seems to be working")
  41. except Exception as e:
  42. typer.echo(
  43. "Error when testing CUDA but USE_CUDA_DOCKER is true. "
  44. "Resetting USE_CUDA_DOCKER to false and removing "
  45. f"LD_LIBRARY_PATH modifications: {e}"
  46. )
  47. os.environ["USE_CUDA_DOCKER"] = "false"
  48. os.environ["LD_LIBRARY_PATH"] = ":".join(LD_LIBRARY_PATH)
  49. import open_webui.main # we need set environment variables before importing main
  50. uvicorn.run(
  51. open_webui.main.app,
  52. host=host,
  53. port=port,
  54. forwarded_allow_ips="*",
  55. log_level=GLOBAL_LOG_LEVEL.lower(),
  56. )
  57. @app.command()
  58. def dev(
  59. host: str = "0.0.0.0",
  60. port: int = 8080,
  61. reload: bool = True,
  62. ):
  63. uvicorn.run(
  64. "open_webui.main:app",
  65. host=host,
  66. port=port,
  67. reload=reload,
  68. forwarded_allow_ips="*",
  69. )
  70. if __name__ == "__main__":
  71. app()