payload.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from open_webui.utils.task import prompt_template
  2. from open_webui.utils.misc import (
  3. add_or_update_system_message,
  4. )
  5. from typing import Callable, Optional
  6. # inplace function: form_data is modified
  7. def apply_model_system_prompt_to_body(params: dict, form_data: dict, user) -> dict:
  8. system = params.get("system", None)
  9. if not system:
  10. return form_data
  11. if user:
  12. template_params = {
  13. "user_name": user.name,
  14. "user_location": user.info.get("location") if user.info else None,
  15. }
  16. else:
  17. template_params = {}
  18. system = prompt_template(system, **template_params)
  19. form_data["messages"] = add_or_update_system_message(
  20. system, form_data.get("messages", [])
  21. )
  22. return form_data
  23. # inplace function: form_data is modified
  24. def apply_model_params_to_body(
  25. params: dict, form_data: dict, mappings: dict[str, Callable]
  26. ) -> dict:
  27. if not params:
  28. return form_data
  29. for key, cast_func in mappings.items():
  30. if (value := params.get(key)) is not None:
  31. form_data[key] = cast_func(value)
  32. return form_data
  33. # inplace function: form_data is modified
  34. def apply_model_params_to_body_openai(params: dict, form_data: dict) -> dict:
  35. mappings = {
  36. "temperature": float,
  37. "top_p": int,
  38. "max_tokens": int,
  39. "frequency_penalty": int,
  40. "seed": lambda x: x,
  41. "stop": lambda x: [bytes(s, "utf-8").decode("unicode_escape") for s in x],
  42. }
  43. return apply_model_params_to_body(params, form_data, mappings)
  44. def apply_model_params_to_body_ollama(params: dict, form_data: dict) -> dict:
  45. opts = [
  46. "temperature",
  47. "top_p",
  48. "seed",
  49. "mirostat",
  50. "mirostat_eta",
  51. "mirostat_tau",
  52. "num_ctx",
  53. "num_batch",
  54. "num_keep",
  55. "repeat_last_n",
  56. "tfs_z",
  57. "top_k",
  58. "min_p",
  59. "use_mmap",
  60. "use_mlock",
  61. "num_thread",
  62. "num_gpu",
  63. ]
  64. mappings = {i: lambda x: x for i in opts}
  65. form_data = apply_model_params_to_body(params, form_data, mappings)
  66. name_differences = {
  67. "max_tokens": "num_predict",
  68. "frequency_penalty": "repeat_penalty",
  69. }
  70. for key, value in name_differences.items():
  71. if (param := params.get(key, None)) is not None:
  72. form_data[value] = param
  73. return form_data