payload.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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": float,
  38. "max_tokens": int,
  39. "frequency_penalty": float,
  40. "reasoning_effort": str,
  41. "seed": lambda x: x,
  42. "stop": lambda x: [bytes(s, "utf-8").decode("unicode_escape") for s in x],
  43. }
  44. return apply_model_params_to_body(params, form_data, mappings)
  45. def apply_model_params_to_body_ollama(params: dict, form_data: dict) -> dict:
  46. opts = [
  47. "temperature",
  48. "top_p",
  49. "seed",
  50. "mirostat",
  51. "mirostat_eta",
  52. "mirostat_tau",
  53. "num_ctx",
  54. "num_batch",
  55. "num_keep",
  56. "repeat_last_n",
  57. "tfs_z",
  58. "top_k",
  59. "min_p",
  60. "use_mmap",
  61. "use_mlock",
  62. "num_thread",
  63. "num_gpu",
  64. ]
  65. mappings = {i: lambda x: x for i in opts}
  66. form_data = apply_model_params_to_body(params, form_data, mappings)
  67. name_differences = {
  68. "max_tokens": "num_predict",
  69. "frequency_penalty": "repeat_penalty",
  70. }
  71. for key, value in name_differences.items():
  72. if (param := params.get(key, None)) is not None:
  73. form_data[value] = param
  74. return form_data
  75. def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
  76. ollama_messages = []
  77. for message in messages:
  78. # Initialize the new message structure with the role
  79. new_message = {"role": message["role"]}
  80. content = message.get("content", [])
  81. # Check if the content is a string (just a simple message)
  82. if isinstance(content, str):
  83. # If the content is a string, it's pure text
  84. new_message["content"] = content
  85. else:
  86. # Otherwise, assume the content is a list of dicts, e.g., text followed by an image URL
  87. content_text = ""
  88. images = []
  89. # Iterate through the list of content items
  90. for item in content:
  91. # Check if it's a text type
  92. if item.get("type") == "text":
  93. content_text += item.get("text", "")
  94. # Check if it's an image URL type
  95. elif item.get("type") == "image_url":
  96. img_url = item.get("image_url", {}).get("url", "")
  97. if img_url:
  98. # If the image url starts with data:, it's a base64 image and should be trimmed
  99. if img_url.startswith("data:"):
  100. img_url = img_url.split(",")[-1]
  101. images.append(img_url)
  102. # Add content text (if any)
  103. if content_text:
  104. new_message["content"] = content_text.strip()
  105. # Add images (if any)
  106. if images:
  107. new_message["images"] = images
  108. # Append the new formatted message to the result
  109. ollama_messages.append(new_message)
  110. return ollama_messages
  111. def convert_payload_openai_to_ollama(openai_payload: dict) -> dict:
  112. """
  113. Converts a payload formatted for OpenAI's API to be compatible with Ollama's API endpoint for chat completions.
  114. Args:
  115. openai_payload (dict): The payload originally designed for OpenAI API usage.
  116. Returns:
  117. dict: A modified payload compatible with the Ollama API.
  118. """
  119. ollama_payload = {}
  120. # Mapping basic model and message details
  121. ollama_payload["model"] = openai_payload.get("model")
  122. ollama_payload["messages"] = convert_messages_openai_to_ollama(
  123. openai_payload.get("messages")
  124. )
  125. ollama_payload["stream"] = openai_payload.get("stream", False)
  126. if "format" in openai_payload:
  127. ollama_payload["format"] = openai_payload["format"]
  128. # If there are advanced parameters in the payload, format them in Ollama's options field
  129. ollama_options = {}
  130. if openai_payload.get("options"):
  131. ollama_payload["options"] = openai_payload["options"]
  132. ollama_options = openai_payload["options"]
  133. # Handle parameters which map directly
  134. for param in ["temperature", "top_p", "seed"]:
  135. if param in openai_payload:
  136. ollama_options[param] = openai_payload[param]
  137. # Mapping OpenAI's `max_tokens` -> Ollama's `num_predict`
  138. if "max_completion_tokens" in openai_payload:
  139. ollama_options["num_predict"] = openai_payload["max_completion_tokens"]
  140. elif "max_tokens" in openai_payload:
  141. ollama_options["num_predict"] = openai_payload["max_tokens"]
  142. # Handle frequency / presence_penalty, which needs renaming and checking
  143. if "frequency_penalty" in openai_payload:
  144. ollama_options["repeat_penalty"] = openai_payload["frequency_penalty"]
  145. if "presence_penalty" in openai_payload and "penalty" not in ollama_options:
  146. # We are assuming presence penalty uses a similar concept in Ollama, which needs custom handling if exists.
  147. ollama_options["new_topic_penalty"] = openai_payload["presence_penalty"]
  148. # Add options to payload if any have been set
  149. if ollama_options:
  150. ollama_payload["options"] = ollama_options
  151. return ollama_payload