payload.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. from open_webui.utils.task import prompt_variables_template
  2. from open_webui.utils.misc import (
  3. add_or_update_system_message,
  4. )
  5. from typing import Callable, Optional
  6. # inplace function: form_data is modified
  7. def apply_model_system_prompt_to_body(
  8. params: dict, form_data: dict, metadata: Optional[dict] = None
  9. ) -> dict:
  10. system = params.get("system", None)
  11. if not system:
  12. return form_data
  13. if metadata:
  14. print("apply_model_system_prompt_to_body: metadata", metadata)
  15. variables = metadata.get("variables", {})
  16. system = prompt_variables_template(system, variables)
  17. form_data["messages"] = add_or_update_system_message(
  18. system, form_data.get("messages", [])
  19. )
  20. return form_data
  21. # inplace function: form_data is modified
  22. def apply_model_params_to_body(
  23. params: dict, form_data: dict, mappings: dict[str, Callable]
  24. ) -> dict:
  25. if not params:
  26. return form_data
  27. for key, cast_func in mappings.items():
  28. if (value := params.get(key)) is not None:
  29. form_data[key] = cast_func(value)
  30. return form_data
  31. # inplace function: form_data is modified
  32. def apply_model_params_to_body_openai(params: dict, form_data: dict) -> dict:
  33. mappings = {
  34. "temperature": float,
  35. "top_p": float,
  36. "max_tokens": int,
  37. "frequency_penalty": float,
  38. "reasoning_effort": str,
  39. "seed": lambda x: x,
  40. "stop": lambda x: [bytes(s, "utf-8").decode("unicode_escape") for s in x],
  41. }
  42. return apply_model_params_to_body(params, form_data, mappings)
  43. def apply_model_params_to_body_ollama(params: dict, form_data: dict) -> dict:
  44. opts = [
  45. "temperature",
  46. "top_p",
  47. "seed",
  48. "mirostat",
  49. "mirostat_eta",
  50. "mirostat_tau",
  51. "num_ctx",
  52. "num_batch",
  53. "num_keep",
  54. "repeat_last_n",
  55. "tfs_z",
  56. "top_k",
  57. "min_p",
  58. "use_mmap",
  59. "use_mlock",
  60. "num_thread",
  61. "num_gpu",
  62. ]
  63. mappings = {i: lambda x: x for i in opts}
  64. form_data = apply_model_params_to_body(params, form_data, mappings)
  65. name_differences = {
  66. "max_tokens": "num_predict",
  67. "frequency_penalty": "repeat_penalty",
  68. }
  69. for key, value in name_differences.items():
  70. if (param := params.get(key, None)) is not None:
  71. form_data[value] = param
  72. return form_data
  73. def convert_messages_openai_to_ollama(messages: list[dict]) -> list[dict]:
  74. ollama_messages = []
  75. for message in messages:
  76. # Initialize the new message structure with the role
  77. new_message = {"role": message["role"]}
  78. content = message.get("content", [])
  79. # Check if the content is a string (just a simple message)
  80. if isinstance(content, str):
  81. # If the content is a string, it's pure text
  82. new_message["content"] = content
  83. else:
  84. # Otherwise, assume the content is a list of dicts, e.g., text followed by an image URL
  85. content_text = ""
  86. images = []
  87. # Iterate through the list of content items
  88. for item in content:
  89. # Check if it's a text type
  90. if item.get("type") == "text":
  91. content_text += item.get("text", "")
  92. # Check if it's an image URL type
  93. elif item.get("type") == "image_url":
  94. img_url = item.get("image_url", {}).get("url", "")
  95. if img_url:
  96. # If the image url starts with data:, it's a base64 image and should be trimmed
  97. if img_url.startswith("data:"):
  98. img_url = img_url.split(",")[-1]
  99. images.append(img_url)
  100. # Add content text (if any)
  101. if content_text:
  102. new_message["content"] = content_text.strip()
  103. # Add images (if any)
  104. if images:
  105. new_message["images"] = images
  106. # Append the new formatted message to the result
  107. ollama_messages.append(new_message)
  108. return ollama_messages
  109. def convert_payload_openai_to_ollama(openai_payload: dict) -> dict:
  110. """
  111. Converts a payload formatted for OpenAI's API to be compatible with Ollama's API endpoint for chat completions.
  112. Args:
  113. openai_payload (dict): The payload originally designed for OpenAI API usage.
  114. Returns:
  115. dict: A modified payload compatible with the Ollama API.
  116. """
  117. ollama_payload = {}
  118. # Mapping basic model and message details
  119. ollama_payload["model"] = openai_payload.get("model")
  120. ollama_payload["messages"] = convert_messages_openai_to_ollama(
  121. openai_payload.get("messages")
  122. )
  123. ollama_payload["stream"] = openai_payload.get("stream", False)
  124. if "format" in openai_payload:
  125. ollama_payload["format"] = openai_payload["format"]
  126. # If there are advanced parameters in the payload, format them in Ollama's options field
  127. ollama_options = {}
  128. if openai_payload.get("options"):
  129. ollama_payload["options"] = openai_payload["options"]
  130. ollama_options = openai_payload["options"]
  131. # Handle parameters which map directly
  132. for param in ["temperature", "top_p", "seed"]:
  133. if param in openai_payload:
  134. ollama_options[param] = openai_payload[param]
  135. # Mapping OpenAI's `max_tokens` -> Ollama's `num_predict`
  136. if "max_completion_tokens" in openai_payload:
  137. ollama_options["num_predict"] = openai_payload["max_completion_tokens"]
  138. elif "max_tokens" in openai_payload:
  139. ollama_options["num_predict"] = openai_payload["max_tokens"]
  140. # Handle frequency / presence_penalty, which needs renaming and checking
  141. if "frequency_penalty" in openai_payload:
  142. ollama_options["repeat_penalty"] = openai_payload["frequency_penalty"]
  143. if "presence_penalty" in openai_payload and "penalty" not in ollama_options:
  144. # We are assuming presence penalty uses a similar concept in Ollama, which needs custom handling if exists.
  145. ollama_options["new_topic_penalty"] = openai_payload["presence_penalty"]
  146. # Add options to payload if any have been set
  147. if ollama_options:
  148. ollama_payload["options"] = ollama_options
  149. if "metadata" in openai_payload:
  150. ollama_payload["metadata"] = openai_payload["metadata"]
  151. return ollama_payload