payload.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. "max_tokens": int,
  48. "frequency_penalty": float,
  49. "reasoning_effort": str,
  50. "seed": lambda x: x,
  51. "stop": lambda x: [bytes(s, "utf-8").decode("unicode_escape") for s in x],
  52. }
  53. return apply_model_params_to_body(params, form_data, mappings)
  54. def apply_model_params_to_body_ollama(params: dict, form_data: dict) -> dict:
  55. opts = [
  56. "temperature",
  57. "top_p",
  58. "seed",
  59. "mirostat",
  60. "mirostat_eta",
  61. "mirostat_tau",
  62. "num_ctx",
  63. "num_batch",
  64. "num_keep",
  65. "repeat_last_n",
  66. "tfs_z",
  67. "top_k",
  68. "min_p",
  69. "use_mmap",
  70. "use_mlock",
  71. "num_thread",
  72. "num_gpu",
  73. ]
  74. mappings = {i: lambda x: x for i in opts}
  75. form_data = apply_model_params_to_body(params, form_data, mappings)
  76. name_differences = {
  77. "max_tokens": "num_predict",
  78. "frequency_penalty": "repeat_penalty",
  79. }
  80. for key, value in name_differences.items():
  81. if (param := params.get(key, None)) is not None:
  82. form_data[value] = param
  83. return form_data
  84. def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
  85. ollama_messages = []
  86. for message in messages:
  87. # Initialize the new message structure with the role
  88. new_message = {"role": message["role"]}
  89. content = message.get("content", [])
  90. tool_calls = message.get("tool_calls", None)
  91. tool_call_id = message.get("tool_call_id", None)
  92. # Check if the content is a string (just a simple message)
  93. if isinstance(content, str):
  94. # If the content is a string, it's pure text
  95. new_message["content"] = content
  96. # If message is a tool call, add the tool call id to the message
  97. if tool_call_id:
  98. new_message["tool_call_id"] = tool_call_id
  99. elif tool_calls:
  100. # If tool calls are present, add them to the message
  101. ollama_tool_calls = []
  102. for tool_call in tool_calls:
  103. ollama_tool_call = {
  104. "index": tool_call.get("index", 0),
  105. "id": tool_call.get("id", None),
  106. "function": {
  107. "name": tool_call.get("function", {}).get("name", ""),
  108. "arguments": json.loads(
  109. tool_call.get("function", {}).get("arguments", {})
  110. ),
  111. },
  112. }
  113. ollama_tool_calls.append(ollama_tool_call)
  114. new_message["tool_calls"] = ollama_tool_calls
  115. # Put the content to empty string (Ollama requires an empty string for tool calls)
  116. new_message["content"] = ""
  117. else:
  118. # Otherwise, assume the content is a list of dicts, e.g., text followed by an image URL
  119. content_text = ""
  120. images = []
  121. # Iterate through the list of content items
  122. for item in content:
  123. # Check if it's a text type
  124. if item.get("type") == "text":
  125. content_text += item.get("text", "")
  126. # Check if it's an image URL type
  127. elif item.get("type") == "image_url":
  128. img_url = item.get("image_url", {}).get("url", "")
  129. if img_url:
  130. # If the image url starts with data:, it's a base64 image and should be trimmed
  131. if img_url.startswith("data:"):
  132. img_url = img_url.split(",")[-1]
  133. images.append(img_url)
  134. # Add content text (if any)
  135. if content_text:
  136. new_message["content"] = content_text.strip()
  137. # Add images (if any)
  138. if images:
  139. new_message["images"] = images
  140. # Append the new formatted message to the result
  141. ollama_messages.append(new_message)
  142. return ollama_messages
  143. def convert_payload_openai_to_ollama(openai_payload: dict) -> dict:
  144. """
  145. Converts a payload formatted for OpenAI's API to be compatible with Ollama's API endpoint for chat completions.
  146. Args:
  147. openai_payload (dict): The payload originally designed for OpenAI API usage.
  148. Returns:
  149. dict: A modified payload compatible with the Ollama API.
  150. """
  151. ollama_payload = {}
  152. # Mapping basic model and message details
  153. ollama_payload["model"] = openai_payload.get("model")
  154. ollama_payload["messages"] = convert_messages_openai_to_ollama(
  155. openai_payload.get("messages")
  156. )
  157. ollama_payload["stream"] = openai_payload.get("stream", False)
  158. if "tools" in openai_payload:
  159. ollama_payload["tools"] = openai_payload["tools"]
  160. if "format" in openai_payload:
  161. ollama_payload["format"] = openai_payload["format"]
  162. # If there are advanced parameters in the payload, format them in Ollama's options field
  163. ollama_options = {}
  164. if openai_payload.get("options"):
  165. ollama_payload["options"] = openai_payload["options"]
  166. ollama_options = openai_payload["options"]
  167. # Handle parameters which map directly
  168. for param in ["temperature", "top_p", "seed"]:
  169. if param in openai_payload:
  170. ollama_options[param] = openai_payload[param]
  171. # Mapping OpenAI's `max_tokens` -> Ollama's `num_predict`
  172. if "max_completion_tokens" in openai_payload:
  173. ollama_options["num_predict"] = openai_payload["max_completion_tokens"]
  174. elif "max_tokens" in openai_payload:
  175. ollama_options["num_predict"] = openai_payload["max_tokens"]
  176. # Handle frequency / presence_penalty, which needs renaming and checking
  177. if "frequency_penalty" in openai_payload:
  178. ollama_options["repeat_penalty"] = openai_payload["frequency_penalty"]
  179. if "presence_penalty" in openai_payload and "penalty" not in ollama_options:
  180. # We are assuming presence penalty uses a similar concept in Ollama, which needs custom handling if exists.
  181. ollama_options["new_topic_penalty"] = openai_payload["presence_penalty"]
  182. # Add options to payload if any have been set
  183. if ollama_options:
  184. ollama_payload["options"] = ollama_options
  185. if "metadata" in openai_payload:
  186. ollama_payload["metadata"] = openai_payload["metadata"]
  187. return ollama_payload