1
0

payload.py 9.4 KB

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