1
0

payload.py 13 KB

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