payload.py 6.2 KB

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