payload.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. from open_webui.utils.task import prompt_template, prompt_variables_template
  2. from open_webui.utils.misc import (
  3. add_or_update_system_message,
  4. )
  5. from typing import Callable, Optional
  6. import json
  7. # inplace function: form_data is modified
  8. def apply_model_system_prompt_to_body(
  9. params: dict, form_data: dict, metadata: Optional[dict] = None, user=None
  10. ) -> dict:
  11. system = params.get("system", None)
  12. if not system:
  13. return form_data
  14. # Metadata (WebUI Usage)
  15. if metadata:
  16. variables = metadata.get("variables", {})
  17. if variables:
  18. system = prompt_variables_template(system, variables)
  19. # Legacy (API Usage)
  20. if user:
  21. template_params = {
  22. "user_name": user.name,
  23. "user_location": user.info.get("location") if user.info else None,
  24. }
  25. else:
  26. template_params = {}
  27. system = prompt_template(system, **template_params)
  28. form_data["messages"] = add_or_update_system_message(
  29. system, form_data.get("messages", [])
  30. )
  31. return form_data
  32. # inplace function: form_data is modified
  33. def apply_model_params_to_body(
  34. params: dict, form_data: dict, mappings: dict[str, Callable]
  35. ) -> dict:
  36. if not params:
  37. return form_data
  38. for key, value in params.items():
  39. if value is not None:
  40. if key in mappings:
  41. cast_func = mappings[key]
  42. if isinstance(cast_func, Callable):
  43. form_data[key] = cast_func(value)
  44. else:
  45. form_data[key] = value
  46. return form_data
  47. # inplace function: form_data is modified
  48. def apply_model_params_to_body_openai(params: dict, form_data: dict) -> dict:
  49. mappings = {
  50. "temperature": float,
  51. "top_p": float,
  52. "min_p": float,
  53. "max_tokens": int,
  54. "frequency_penalty": float,
  55. "presence_penalty": float,
  56. "reasoning_effort": str,
  57. "seed": lambda x: x,
  58. "stop": lambda x: [bytes(s, "utf-8").decode("unicode_escape") for s in x],
  59. "logit_bias": lambda x: x,
  60. "response_format": dict,
  61. }
  62. return apply_model_params_to_body(params, form_data, mappings)
  63. def apply_model_params_to_body_ollama(params: dict, form_data: dict) -> dict:
  64. # Convert OpenAI parameter names to Ollama parameter names if needed.
  65. name_differences = {
  66. "max_tokens": "num_predict",
  67. }
  68. for key, value in name_differences.items():
  69. if (param := params.get(key, None)) is not None:
  70. # Copy the parameter to new name then delete it, to prevent Ollama warning of invalid option provided
  71. params[value] = params[key]
  72. del params[key]
  73. # See https://github.com/ollama/ollama/blob/main/docs/api.md#request-8
  74. mappings = {
  75. "temperature": float,
  76. "top_p": float,
  77. "seed": lambda x: x,
  78. "mirostat": int,
  79. "mirostat_eta": float,
  80. "mirostat_tau": float,
  81. "num_ctx": int,
  82. "num_batch": int,
  83. "num_keep": int,
  84. "num_predict": int,
  85. "repeat_last_n": int,
  86. "top_k": int,
  87. "min_p": float,
  88. "typical_p": float,
  89. "repeat_penalty": float,
  90. "presence_penalty": float,
  91. "frequency_penalty": float,
  92. "penalize_newline": bool,
  93. "stop": lambda x: [bytes(s, "utf-8").decode("unicode_escape") for s in x],
  94. "numa": bool,
  95. "num_gpu": int,
  96. "main_gpu": int,
  97. "low_vram": bool,
  98. "vocab_only": bool,
  99. "use_mmap": bool,
  100. "use_mlock": bool,
  101. "num_thread": int,
  102. }
  103. # Extract keep_alive from options if it exists
  104. if "options" in form_data and "keep_alive" in form_data["options"]:
  105. form_data["keep_alive"] = form_data["options"]["keep_alive"]
  106. del form_data["options"]["keep_alive"]
  107. if "options" in form_data and "format" in form_data["options"]:
  108. form_data["format"] = form_data["options"]["format"]
  109. del form_data["options"]["format"]
  110. return apply_model_params_to_body(params, form_data, mappings)
  111. def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
  112. ollama_messages = []
  113. for message in messages:
  114. # Initialize the new message structure with the role
  115. new_message = {"role": message["role"]}
  116. content = message.get("content", [])
  117. tool_calls = message.get("tool_calls", None)
  118. tool_call_id = message.get("tool_call_id", None)
  119. # Check if the content is a string (just a simple message)
  120. if isinstance(content, str) and not tool_calls:
  121. # If the content is a string, it's pure text
  122. new_message["content"] = content
  123. # If message is a tool call, add the tool call id to the message
  124. if tool_call_id:
  125. new_message["tool_call_id"] = tool_call_id
  126. elif tool_calls:
  127. # If tool calls are present, add them to the message
  128. ollama_tool_calls = []
  129. for tool_call in tool_calls:
  130. ollama_tool_call = {
  131. "index": tool_call.get("index", 0),
  132. "id": tool_call.get("id", None),
  133. "function": {
  134. "name": tool_call.get("function", {}).get("name", ""),
  135. "arguments": json.loads(
  136. tool_call.get("function", {}).get("arguments", {})
  137. ),
  138. },
  139. }
  140. ollama_tool_calls.append(ollama_tool_call)
  141. new_message["tool_calls"] = ollama_tool_calls
  142. # Put the content to empty string (Ollama requires an empty string for tool calls)
  143. new_message["content"] = ""
  144. else:
  145. # Otherwise, assume the content is a list of dicts, e.g., text followed by an image URL
  146. content_text = ""
  147. images = []
  148. # Iterate through the list of content items
  149. for item in content:
  150. # Check if it's a text type
  151. if item.get("type") == "text":
  152. content_text += item.get("text", "")
  153. # Check if it's an image URL type
  154. elif item.get("type") == "image_url":
  155. img_url = item.get("image_url", {}).get("url", "")
  156. if img_url:
  157. # If the image url starts with data:, it's a base64 image and should be trimmed
  158. if img_url.startswith("data:"):
  159. img_url = img_url.split(",")[-1]
  160. images.append(img_url)
  161. # Add content text (if any)
  162. if content_text:
  163. new_message["content"] = content_text.strip()
  164. # Add images (if any)
  165. if images:
  166. new_message["images"] = images
  167. # Append the new formatted message to the result
  168. ollama_messages.append(new_message)
  169. return ollama_messages
  170. def convert_payload_openai_to_ollama(openai_payload: dict) -> dict:
  171. """
  172. Converts a payload formatted for OpenAI's API to be compatible with Ollama's API endpoint for chat completions.
  173. Args:
  174. openai_payload (dict): The payload originally designed for OpenAI API usage.
  175. Returns:
  176. dict: A modified payload compatible with the Ollama API.
  177. """
  178. ollama_payload = {}
  179. # Mapping basic model and message details
  180. ollama_payload["model"] = openai_payload.get("model")
  181. ollama_payload["messages"] = convert_messages_openai_to_ollama(
  182. openai_payload.get("messages")
  183. )
  184. ollama_payload["stream"] = openai_payload.get("stream", False)
  185. if "tools" in openai_payload:
  186. ollama_payload["tools"] = openai_payload["tools"]
  187. if "format" in openai_payload:
  188. ollama_payload["format"] = openai_payload["format"]
  189. # If there are advanced parameters in the payload, format them in Ollama's options field
  190. if openai_payload.get("options"):
  191. ollama_payload["options"] = openai_payload["options"]
  192. ollama_options = openai_payload["options"]
  193. # Re-Mapping OpenAI's `max_tokens` -> Ollama's `num_predict`
  194. if "max_tokens" in ollama_options:
  195. ollama_options["num_predict"] = ollama_options["max_tokens"]
  196. del ollama_options[
  197. "max_tokens"
  198. ] # To prevent Ollama warning of invalid option provided
  199. # Ollama lacks a "system" prompt option. It has to be provided as a direct parameter, so we copy it down.
  200. if "system" in ollama_options:
  201. ollama_payload["system"] = ollama_options["system"]
  202. del ollama_options[
  203. "system"
  204. ] # To prevent Ollama warning of invalid option provided
  205. # Extract keep_alive from options if it exists
  206. if "keep_alive" in ollama_options:
  207. ollama_payload["keep_alive"] = ollama_options["keep_alive"]
  208. del ollama_options["keep_alive"]
  209. # If there is the "stop" parameter in the openai_payload, remap it to the ollama_payload.options
  210. if "stop" in openai_payload:
  211. ollama_options = ollama_payload.get("options", {})
  212. ollama_options["stop"] = openai_payload.get("stop")
  213. ollama_payload["options"] = ollama_options
  214. if "metadata" in openai_payload:
  215. ollama_payload["metadata"] = openai_payload["metadata"]
  216. if "response_format" in openai_payload:
  217. response_format = openai_payload["response_format"]
  218. format_type = response_format.get("type", None)
  219. schema = response_format.get(format_type, None)
  220. if schema:
  221. format = schema.get("schema", None)
  222. ollama_payload["format"] = format
  223. return ollama_payload