payload.py 13 KB

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