models.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from __future__ import annotations
  2. import os
  3. import requests
  4. import json
  5. from ..requests.raise_for_status import raise_for_status
  6. def load_models():
  7. response = requests.get("https://gpt4all.io/models/models3.json")
  8. raise_for_status(response)
  9. return format_models(response.json())
  10. def get_model_name(filename: str) -> str:
  11. name = filename.split(".", 1)[0]
  12. for replace in ["-v1_5", "-v1", "-q4_0", "_v01", "-v0", "-f16", "-gguf2", "-newbpe"]:
  13. name = name.replace(replace, "")
  14. return name
  15. def format_models(models: list) -> dict:
  16. return {get_model_name(model["filename"]): {
  17. "path": model["filename"],
  18. "ram": model["ramrequired"],
  19. "prompt": model["promptTemplate"] if "promptTemplate" in model else None,
  20. "system": model["systemPrompt"] if "systemPrompt" in model else None,
  21. } for model in models}
  22. def read_models(file_path: str):
  23. with open(file_path, "rb") as f:
  24. return json.load(f)
  25. def save_models(file_path: str, data):
  26. with open(file_path, 'w') as f:
  27. json.dump(data, f, indent=4)
  28. def get_model_dir() -> str:
  29. local_dir = os.path.dirname(os.path.abspath(__file__))
  30. project_dir = os.path.dirname(os.path.dirname(local_dir))
  31. model_dir = os.path.join(project_dir, "models")
  32. if not os.path.exists(model_dir):
  33. os.mkdir(model_dir)
  34. return model_dir
  35. def get_models() -> dict[str, dict]:
  36. model_dir = get_model_dir()
  37. file_path = os.path.join(model_dir, "models.json")
  38. if os.path.isfile(file_path):
  39. return read_models(file_path)
  40. else:
  41. models = load_models()
  42. save_models(file_path, models)
  43. return models