mirror of
https://github.com/open-webui/pipelines
synced 2025-05-11 16:10:45 +00:00
Merge branch 'open-webui:main' into main
This commit is contained in:
commit
7e8992de81
@ -1,4 +1,13 @@
|
|||||||
"""A manifold to integrate Google's GenAI models into Open-WebUI"""
|
"""
|
||||||
|
title: Google GenAI Manifold Pipeline
|
||||||
|
author: Marc Lopez (refactor by justinh-rahb)
|
||||||
|
date: 2024-06-06
|
||||||
|
version: 1.1
|
||||||
|
license: MIT
|
||||||
|
description: A pipeline for generating text using Google's GenAI models in Open-WebUI.
|
||||||
|
requirements: google-generativeai
|
||||||
|
environment_variables: GOOGLE_API_KEY
|
||||||
|
"""
|
||||||
|
|
||||||
from typing import List, Union, Iterator
|
from typing import List, Union, Iterator
|
||||||
import os
|
import os
|
||||||
@ -6,6 +15,7 @@ import os
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
import google.generativeai as genai
|
import google.generativeai as genai
|
||||||
|
from google.generativeai.types import GenerationConfig
|
||||||
|
|
||||||
|
|
||||||
class Pipeline:
|
class Pipeline:
|
||||||
@ -72,56 +82,78 @@ class Pipeline:
|
|||||||
def pipe(
|
def pipe(
|
||||||
self, user_message: str, model_id: str, messages: List[dict], body: dict
|
self, user_message: str, model_id: str, messages: List[dict], body: dict
|
||||||
) -> Union[str, Iterator]:
|
) -> Union[str, Iterator]:
|
||||||
"""The pipe function (connects open-webui to google-genai)
|
if not self.valves.GOOGLE_API_KEY:
|
||||||
|
return "Error: GOOGLE_API_KEY is not set"
|
||||||
|
|
||||||
Args:
|
try:
|
||||||
user_message (str): The last message input by the user
|
genai.configure(api_key=self.valves.GOOGLE_API_KEY)
|
||||||
model_id (str): The model to use
|
|
||||||
messages (List[dict]): The chat history
|
|
||||||
body (dict): The raw request body in OpenAI's "chat/completions" style
|
|
||||||
|
|
||||||
Returns:
|
if model_id.startswith("google_genai."):
|
||||||
str: The complete response
|
model_id = model_id[12:]
|
||||||
|
model_id = model_id.lstrip(".")
|
||||||
|
|
||||||
Yields:
|
if not model_id.startswith("gemini-"):
|
||||||
Iterator[str]: Yields a new message part every time it is received
|
return f"Error: Invalid model name format: {model_id}"
|
||||||
"""
|
|
||||||
|
|
||||||
print(f"pipe:{__name__}")
|
print(f"Pipe function called for model: {model_id}")
|
||||||
|
print(f"Stream mode: {body.get('stream', False)}")
|
||||||
|
|
||||||
system_prompt = None
|
system_message = next((msg["content"] for msg in messages if msg["role"] == "system"), None)
|
||||||
google_messages = []
|
|
||||||
|
contents = []
|
||||||
for message in messages:
|
for message in messages:
|
||||||
google_role = ""
|
if message["role"] != "system":
|
||||||
if message["role"] == "user":
|
if isinstance(message.get("content"), list):
|
||||||
google_role = "user"
|
parts = []
|
||||||
elif message["role"] == "assistant":
|
for content in message["content"]:
|
||||||
google_role = "model"
|
if content["type"] == "text":
|
||||||
elif message["role"] == "system":
|
parts.append({"text": content["text"]})
|
||||||
system_prompt = message["content"]
|
elif content["type"] == "image_url":
|
||||||
continue # System promt is not inyected as a message
|
image_url = content["image_url"]["url"]
|
||||||
google_messages.append(
|
if image_url.startswith("data:image"):
|
||||||
genai.protos.Content(
|
image_data = image_url.split(",")[1]
|
||||||
role=google_role,
|
parts.append({"inline_data": {"mime_type": "image/jpeg", "data": image_data}})
|
||||||
parts=[
|
else:
|
||||||
genai.protos.Part(
|
parts.append({"image_url": image_url})
|
||||||
text=message["content"],
|
contents.append({"role": message["role"], "parts": parts})
|
||||||
),
|
else:
|
||||||
],
|
contents.append({
|
||||||
)
|
"role": "user" if message["role"] == "user" else "model",
|
||||||
|
"parts": [{"text": message["content"]}]
|
||||||
|
})
|
||||||
|
|
||||||
|
if system_message:
|
||||||
|
contents.insert(0, {"role": "user", "parts": [{"text": f"System: {system_message}"}]})
|
||||||
|
|
||||||
|
model = genai.GenerativeModel(model_name=model_id)
|
||||||
|
|
||||||
|
generation_config = GenerationConfig(
|
||||||
|
temperature=body.get("temperature", 0.7),
|
||||||
|
top_p=body.get("top_p", 0.9),
|
||||||
|
top_k=body.get("top_k", 40),
|
||||||
|
max_output_tokens=body.get("max_tokens", 8192),
|
||||||
|
stop_sequences=body.get("stop", []),
|
||||||
)
|
)
|
||||||
|
|
||||||
response = genai.GenerativeModel(
|
safety_settings = body.get("safety_settings")
|
||||||
f"models/{model_id}", # we have to add the "models/" part again
|
|
||||||
system_instruction=system_prompt,
|
response = model.generate_content(
|
||||||
).generate_content(
|
contents,
|
||||||
google_messages,
|
generation_config=generation_config,
|
||||||
stream=body["stream"],
|
safety_settings=safety_settings,
|
||||||
|
stream=body.get("stream", False),
|
||||||
)
|
)
|
||||||
|
|
||||||
if body["stream"]:
|
if body.get("stream", False):
|
||||||
for chunk in response:
|
return self.stream_response(response)
|
||||||
yield chunk.text
|
else:
|
||||||
return ""
|
|
||||||
|
|
||||||
return response.text
|
return response.text
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error generating content: {e}")
|
||||||
|
return f"An error occurred: {str(e)}"
|
||||||
|
|
||||||
|
def stream_response(self, response):
|
||||||
|
for chunk in response:
|
||||||
|
if chunk.text:
|
||||||
|
yield chunk.text
|
||||||
|
Loading…
Reference in New Issue
Block a user