payload.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. from open_webui.utils.task import prompt_template, prompt_variables_template
  2. from open_webui.utils.misc import (
  3. deep_update,
  4. add_or_update_system_message,
  5. )
  6. from typing import Callable, Optional
  7. import json
  8. # inplace function: form_data is modified
  9. def apply_system_prompt_to_body(
  10. system: Optional[str], form_data: dict, metadata: Optional[dict] = None, user=None
  11. ) -> dict:
  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. system = prompt_template(system, user)
  21. form_data["messages"] = add_or_update_system_message(
  22. system, form_data.get("messages", [])
  23. )
  24. return form_data
  25. # inplace function: form_data is modified
  26. def apply_model_params_to_body(
  27. params: dict, form_data: dict, mappings: dict[str, Callable]
  28. ) -> dict:
  29. if not params:
  30. return form_data
  31. for key, value in params.items():
  32. if value is not None:
  33. if key in mappings:
  34. cast_func = mappings[key]
  35. if isinstance(cast_func, Callable):
  36. form_data[key] = cast_func(value)
  37. else:
  38. form_data[key] = value
  39. return form_data
  40. def remove_open_webui_params(params: dict) -> dict:
  41. """
  42. Removes OpenWebUI specific parameters from the provided dictionary.
  43. Args:
  44. params (dict): The dictionary containing parameters.
  45. Returns:
  46. dict: The modified dictionary with OpenWebUI parameters removed.
  47. """
  48. open_webui_params = {
  49. "stream_response": bool,
  50. "stream_delta_chunk_size": int,
  51. "function_calling": str,
  52. "reasoning_tags": list,
  53. "system": str,
  54. }
  55. for key in list(params.keys()):
  56. if key in open_webui_params:
  57. del params[key]
  58. return params
  59. # inplace function: form_data is modified
  60. def apply_model_params_to_body_openai(params: dict, form_data: dict) -> dict:
  61. params = remove_open_webui_params(params)
  62. custom_params = params.pop("custom_params", {})
  63. if custom_params:
  64. # Attempt to parse custom_params if they are strings
  65. for key, value in custom_params.items():
  66. if isinstance(value, str):
  67. try:
  68. # Attempt to parse the string as JSON
  69. custom_params[key] = json.loads(value)
  70. except json.JSONDecodeError:
  71. # If it fails, keep the original string
  72. pass
  73. # If there are custom parameters, we need to apply them first
  74. params = deep_update(params, custom_params)
  75. mappings = {
  76. "temperature": float,
  77. "top_p": float,
  78. "min_p": float,
  79. "max_tokens": int,
  80. "frequency_penalty": float,
  81. "presence_penalty": float,
  82. "reasoning_effort": str,
  83. "seed": lambda x: x,
  84. "stop": lambda x: [bytes(s, "utf-8").decode("unicode_escape") for s in x],
  85. "logit_bias": lambda x: x,
  86. "response_format": dict,
  87. }
  88. return apply_model_params_to_body(params, form_data, mappings)
  89. def apply_model_params_to_body_ollama(params: dict, form_data: dict) -> dict:
  90. params = remove_open_webui_params(params)
  91. custom_params = params.pop("custom_params", {})
  92. if custom_params:
  93. # Attempt to parse custom_params if they are strings
  94. for key, value in custom_params.items():
  95. if isinstance(value, str):
  96. try:
  97. # Attempt to parse the string as JSON
  98. custom_params[key] = json.loads(value)
  99. except json.JSONDecodeError:
  100. # If it fails, keep the original string
  101. pass
  102. # If there are custom parameters, we need to apply them first
  103. params = deep_update(params, custom_params)
  104. # Convert OpenAI parameter names to Ollama parameter names if needed.
  105. name_differences = {
  106. "max_tokens": "num_predict",
  107. }
  108. for key, value in name_differences.items():
  109. if (param := params.get(key, None)) is not None:
  110. # Copy the parameter to new name then delete it, to prevent Ollama warning of invalid option provided
  111. params[value] = params[key]
  112. del params[key]
  113. # See https://github.com/ollama/ollama/blob/main/docs/api.md#request-8
  114. mappings = {
  115. "temperature": float,
  116. "top_p": float,
  117. "seed": lambda x: x,
  118. "mirostat": int,
  119. "mirostat_eta": float,
  120. "mirostat_tau": float,
  121. "num_ctx": int,
  122. "num_batch": int,
  123. "num_keep": int,
  124. "num_predict": int,
  125. "repeat_last_n": int,
  126. "top_k": int,
  127. "min_p": float,
  128. "typical_p": float,
  129. "repeat_penalty": float,
  130. "presence_penalty": float,
  131. "frequency_penalty": float,
  132. "penalize_newline": bool,
  133. "stop": lambda x: [bytes(s, "utf-8").decode("unicode_escape") for s in x],
  134. "numa": bool,
  135. "num_gpu": int,
  136. "main_gpu": int,
  137. "low_vram": bool,
  138. "vocab_only": bool,
  139. "use_mmap": bool,
  140. "use_mlock": bool,
  141. "num_thread": int,
  142. }
  143. def parse_json(value: str) -> dict:
  144. """
  145. Parses a JSON string into a dictionary, handling potential JSONDecodeError.
  146. """
  147. try:
  148. return json.loads(value)
  149. except Exception as e:
  150. return value
  151. ollama_root_params = {
  152. "format": lambda x: parse_json(x),
  153. "keep_alive": lambda x: parse_json(x),
  154. "think": bool,
  155. }
  156. for key, value in ollama_root_params.items():
  157. if (param := params.get(key, None)) is not None:
  158. # Copy the parameter to new name then delete it, to prevent Ollama warning of invalid option provided
  159. form_data[key] = value(param)
  160. del params[key]
  161. # Unlike OpenAI, Ollama does not support params directly in the body
  162. form_data["options"] = apply_model_params_to_body(
  163. params, (form_data.get("options", {}) or {}), mappings
  164. )
  165. return form_data
  166. def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
  167. ollama_messages = []
  168. for message in messages:
  169. # Initialize the new message structure with the role
  170. new_message = {"role": message["role"]}
  171. content = message.get("content", [])
  172. tool_calls = message.get("tool_calls", None)
  173. tool_call_id = message.get("tool_call_id", None)
  174. # Check if the content is a string (just a simple message)
  175. if isinstance(content, str) and not tool_calls:
  176. # If the content is a string, it's pure text
  177. new_message["content"] = content
  178. # If message is a tool call, add the tool call id to the message
  179. if tool_call_id:
  180. new_message["tool_call_id"] = tool_call_id
  181. elif tool_calls:
  182. # If tool calls are present, add them to the message
  183. ollama_tool_calls = []
  184. for tool_call in tool_calls:
  185. ollama_tool_call = {
  186. "index": tool_call.get("index", 0),
  187. "id": tool_call.get("id", None),
  188. "function": {
  189. "name": tool_call.get("function", {}).get("name", ""),
  190. "arguments": json.loads(
  191. tool_call.get("function", {}).get("arguments", {})
  192. ),
  193. },
  194. }
  195. ollama_tool_calls.append(ollama_tool_call)
  196. new_message["tool_calls"] = ollama_tool_calls
  197. # Put the content to empty string (Ollama requires an empty string for tool calls)
  198. new_message["content"] = ""
  199. else:
  200. # Otherwise, assume the content is a list of dicts, e.g., text followed by an image URL
  201. content_text = ""
  202. images = []
  203. # Iterate through the list of content items
  204. for item in content:
  205. # Check if it's a text type
  206. if item.get("type") == "text":
  207. content_text += item.get("text", "")
  208. # Check if it's an image URL type
  209. elif item.get("type") == "image_url":
  210. img_url = item.get("image_url", {}).get("url", "")
  211. if img_url:
  212. # If the image url starts with data:, it's a base64 image and should be trimmed
  213. if img_url.startswith("data:"):
  214. img_url = img_url.split(",")[-1]
  215. images.append(img_url)
  216. # Add content text (if any)
  217. if content_text:
  218. new_message["content"] = content_text.strip()
  219. # Add images (if any)
  220. if images:
  221. new_message["images"] = images
  222. # Append the new formatted message to the result
  223. ollama_messages.append(new_message)
  224. return ollama_messages
  225. def convert_payload_openai_to_ollama(openai_payload: dict) -> dict:
  226. """
  227. Converts a payload formatted for OpenAI's API to be compatible with Ollama's API endpoint for chat completions.
  228. Args:
  229. openai_payload (dict): The payload originally designed for OpenAI API usage.
  230. Returns:
  231. dict: A modified payload compatible with the Ollama API.
  232. """
  233. ollama_payload = {}
  234. # Mapping basic model and message details
  235. ollama_payload["model"] = openai_payload.get("model")
  236. ollama_payload["messages"] = convert_messages_openai_to_ollama(
  237. openai_payload.get("messages")
  238. )
  239. ollama_payload["stream"] = openai_payload.get("stream", False)
  240. if "tools" in openai_payload:
  241. ollama_payload["tools"] = openai_payload["tools"]
  242. # If there are advanced parameters in the payload, format them in Ollama's options field
  243. if openai_payload.get("options"):
  244. ollama_payload["options"] = openai_payload["options"]
  245. ollama_options = openai_payload["options"]
  246. def parse_json(value: str) -> dict:
  247. """
  248. Parses a JSON string into a dictionary, handling potential JSONDecodeError.
  249. """
  250. try:
  251. return json.loads(value)
  252. except Exception as e:
  253. return value
  254. ollama_root_params = {
  255. "format": lambda x: parse_json(x),
  256. "keep_alive": lambda x: parse_json(x),
  257. "think": bool,
  258. }
  259. # Ollama's options field can contain parameters that should be at the root level.
  260. for key, value in ollama_root_params.items():
  261. if (param := ollama_options.get(key, None)) is not None:
  262. # Copy the parameter to new name then delete it, to prevent Ollama warning of invalid option provided
  263. ollama_payload[key] = value(param)
  264. del ollama_options[key]
  265. # Re-Mapping OpenAI's `max_tokens` -> Ollama's `num_predict`
  266. if "max_tokens" in ollama_options:
  267. ollama_options["num_predict"] = ollama_options["max_tokens"]
  268. del ollama_options["max_tokens"]
  269. # Ollama lacks a "system" prompt option. It has to be provided as a direct parameter, so we copy it down.
  270. # Comment: Not sure why this is needed, but we'll keep it for compatibility.
  271. if "system" in ollama_options:
  272. ollama_payload["system"] = ollama_options["system"]
  273. del ollama_options["system"]
  274. ollama_payload["options"] = ollama_options
  275. # If there is the "stop" parameter in the openai_payload, remap it to the ollama_payload.options
  276. if "stop" in openai_payload:
  277. ollama_options = ollama_payload.get("options", {})
  278. ollama_options["stop"] = openai_payload.get("stop")
  279. ollama_payload["options"] = ollama_options
  280. if "metadata" in openai_payload:
  281. ollama_payload["metadata"] = openai_payload["metadata"]
  282. if "response_format" in openai_payload:
  283. response_format = openai_payload["response_format"]
  284. format_type = response_format.get("type", None)
  285. schema = response_format.get(format_type, None)
  286. if schema:
  287. format = schema.get("schema", None)
  288. ollama_payload["format"] = format
  289. return ollama_payload
  290. def convert_embedding_payload_openai_to_ollama(openai_payload: dict) -> dict:
  291. """
  292. Convert an embeddings request payload from OpenAI format to Ollama format.
  293. Args:
  294. openai_payload (dict): The original payload designed for OpenAI API usage.
  295. Returns:
  296. dict: A payload compatible with the Ollama API embeddings endpoint.
  297. """
  298. ollama_payload = {"model": openai_payload.get("model")}
  299. input_value = openai_payload.get("input")
  300. # Ollama expects 'input' as a list, and 'prompt' as a single string.
  301. if isinstance(input_value, list):
  302. ollama_payload["input"] = input_value
  303. ollama_payload["prompt"] = "\n".join(str(x) for x in input_value)
  304. else:
  305. ollama_payload["input"] = [input_value]
  306. ollama_payload["prompt"] = str(input_value)
  307. # Optionally forward other fields if present
  308. for optional_key in ("options", "truncate", "keep_alive"):
  309. if optional_key in openai_payload:
  310. ollama_payload[optional_key] = openai_payload[optional_key]
  311. return ollama_payload