__init__.py 2.6 KB

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