Given this documentation, can you help me write a filter function for open webui?
🪄 Filter Function: Modify Inputs and Outputs
Welcome to the comprehensive guide on Filter Functions in Open WebUI! Filters are a flexible and powerful plugin system for modifying data before it's sent to the Large Language Model (LLM) (input) or after it’s returned from the LLM (output). Whether you’re transforming inputs for better context or cleaning up outputs for improved readability, Filter Functions let you do it all.
This guide will break down what Filters are, how they work, their structure, and everything you need to know to build powerful and user-friendly filters of your own. Let’s dig in, and don’t worry—I’ll use metaphors, examples, and tips to make everything crystal clear! 🌟
🌊 What Are Filters in Open WebUI?
Imagine Open WebUI as a stream of water flowing through pipes:
code
User inputs and LLM outputs are the water.
Filters are the water treatment stages that clean, modify, and adapt the water before it reaches the final destination.
Filters sit in the middle of the flow—like checkpoints—where you decide what needs to be adjusted.
Here’s a quick summary of what Filters do:
code
Modify User Inputs (Inlet Function): Tweak the input data before it reaches the AI model. This is where you enhance clarity, add context, sanitize text, or reformat messages to match specific requirements.
Intercept Model Outputs (Stream Function): Capture and adjust the AI’s responses as they’re generated by the model. This is useful for real-time modifications, like filtering out sensitive information or formatting the output for better readability.
Modify Model Outputs (Outlet Function): Adjust the AI's response after it’s processed, before showing it to the user. This can help refine, log, or adapt the data for a cleaner user experience.
Key Concept: Filters are not standalone models but tools that enhance or transform the data traveling to and from models.
Filters are like translators or editors in the AI workflow: you can intercept and change the conversation without interrupting the flow.
🗺️ Structure of a Filter Function: The Skeleton
Let's start with the simplest representation of a Filter Function. Don't worry if some parts feel technical at first—we’ll break it all down step by step!
🦴 Basic Skeleton of a Filter
from pydantic import BaseModel
from typing import Optional
class Filter:
# Valves: Configuration options for the filter
class Valves(BaseModel):
pass
code
def __init__(self):
# Initialize valves (optional configuration for the Filter)
self.valves = self.Valves()
def inlet(self, body: dict) -> dict:
# This is where you manipulate user inputs.
print(f"inlet called: {body}")
return body
def stream(self, event: dict) -> dict:
# This is where you modify streamed chunks of model output.
print(f"stream event: {event}")
return event
def outlet(self, body: dict) -> None:
# This is where you manipulate model outputs.
print(f"outlet called: {body}")
🎯 Key Components Explained
1️⃣ Valves Class (Optional Settings)
Think of Valves as the knobs and sliders for your filter. If you want to give users configurable options to adjust your Filter’s behavior, you define those here.
class Valves(BaseModel):
OPTION_NAME: str = "Default Value"
For example:
If you're creating a filter that converts responses into uppercase, you might allow users to configure whether every output gets totally capitalized via a valve like TRANSFORM_UPPERCASE: bool = True/False.
2️⃣ inlet Function (Input Pre-Processing)
The inlet function is like prepping food before cooking. Imagine you’re a chef: before the ingredients go into the recipe (the LLM in this case), you might wash vegetables, chop onions, or season the meat. Without this step, your final dish could lack flavor, have unwashed produce, or simply be inconsistent.
In the world of Open WebUI, the inlet function does this important prep work on the user input before it’s sent to the model. It ensures the input is as clean, contextual, and helpful as possible for the AI to handle.
📥 Input:
code
body: The raw input from Open WebUI to the model. It is in the format of a chat-completion request (usually a dictionary that includes fields like the conversation's messages, model settings, and other metadata). Think of this as your recipe ingredients.
🚀 Your Task:
Modify and return the body. The modified version of the body is what the LLM works with, so this is your chance to bring clarity, structure, and context to the input.
🍳 Why Would You Use the inlet?
code
Adding Context: Automatically append crucial information to the user’s input, especially if their text is vague or incomplete. For example, you might add "You are a friendly assistant" or "Help this user troubleshoot a software bug."
Formatting Data: If the input requires a specific format, like JSON or Markdown, you can transform it before sending it to the model.
Sanitizing Input: Remove unwanted characters, strip potentially harmful or confusing symbols (like excessive whitespace or emojis), or replace sensitive information.
Streamlining User Input: If your model’s output improves with additional guidance, you can use the inlet to inject clarifying instructions automatically!
💡 Example Use Cases: Build on Food Prep
🥗 Example 1: Adding System Context
Let’s say the LLM is a chef preparing a dish for Italian cuisine, but the user hasn’t mentioned "This is for Italian cooking." You can ensure the message is clear by appending this context before sending the data to the model.
def inlet(self, body: dict, user: Optional[dict] = None) -> dict:
# Add system message for Italian context in the conversation
context_message = {
"role": "system",
"content": "You are helping the user prepare an Italian meal."
}
# Insert the context at the beginning of the chat history
body.setdefault("messages", []).insert(0, context_message)
return body
📖 What Happens?
code
Any user input like "What are some good dinner ideas?" now carries the Italian theme because we’ve set the system context! Cheesecake might not show up as an answer, but pasta sure will.
🔪 Example 2: Cleaning Input (Remove Odd Characters)
Suppose the input from the user looks messy or includes unwanted symbols like !!!, making the conversation inefficient or harder for the model to parse. You can clean it up while preserving the core content.
def inlet(self, body: dict, user: Optional[dict] = None) -> dict:
# Clean the last user input (from the end of the 'messages' list)
last_message = body["messages"][-1]["content"]
body["messages"][-1]["content"] = last_message.replace("!!!", "").strip()
return body
📖 What Happens?
code
Before: "How can I debug this issue!!!" ➡️ Sent to the model as "How can I debug this issue"
Note: The user feels the same, but the model processes a cleaner and easier-to-understand query.
📊 How inlet Helps Optimize Input for the LLM:
code
Improves accuracy by clarifying ambiguous queries.
Makes the AI more efficient by removing unnecessary noise like emojis, HTML tags, or extra punctuation.
Ensures consistency by formatting user input to match the model’s expected patterns or schemas (like, say, JSON for a specific use case).
💭 Think of inlet as the sous-chef in your kitchen—ensuring everything that goes into the model (your AI "recipe") has been prepped, cleaned, and seasoned to perfection. The better the input, the better the output!
🆕 3️⃣ stream Hook (New in Open WebUI 0.5.17)
🔄 What is the stream Hook?
The stream function is a new feature introduced in Open WebUI 0.5.17 that allows you to intercept and modify streamed model responses in real time.
Unlike outlet, which processes an entire completed response, stream operates on individual chunks as they are received from the model.
🛠️ When to Use the Stream Hook?
code
Modify streaming responses before they are displayed to users.
Implement real-time censorship or cleanup.
Monitor streamed data for logging/debugging.
📜 Example: Logging Streaming Chunks
Here’s how you can inspect and modify streamed LLM responses:
def stream(self, event: dict) -> dict:
print(event) # Print each incoming chunk for inspection
return event
The outlet function is like a proofreader: tidy up the AI's response (or make final changes) after it’s processed by the LLM.
📤 Input:
code
body: This contains all current messages in the chat (user history + LLM replies).
🚀 Your Task: Modify this body. You can clean, append, or log changes, but be mindful of how each adjustment impacts the user experience.
💡 Best Practices:
code
Prefer logging over direct edits in the outlet (e.g., for debugging or analytics).
If heavy modifications are needed (like formatting outputs), consider using the pipe function instead.
💡 Example Use Case: Strip out sensitive API responses you don't want the user to see:
def outlet(self, body: dict, user: Optional[dict] = None) -> dict:
for message in body["messages"]:
message["content"] = message["content"].replace("<API_KEY>", "[REDACTED]")
return body
🌟 Filters in Action: Building Practical Examples
Let’s build some real-world examples to see how you’d use Filters!
📚 Example #1: Add Context to Every User Input
Want the LLM to always know it's assisting a customer in troubleshooting software bugs? You can add instructions like "You're a software troubleshooting assistant" to every user query.
class Filter:
def inlet(self, body: dict, user: Optional[dict] = None) -> dict:
context_message = {
"role": "system",
"content": "You're a software troubleshooting assistant."
}
body.setdefault("messages", []).insert(0, context_message)
return body
📚 Example #2: Highlight Outputs for Easy Reading
Returning output in Markdown or another formatted style? Use the outlet function!
class Filter:
def outlet(self, body: dict, user: Optional[dict] = None) -> dict:
# Add "highlight" markdown for every response
for message in body["messages"]:
if message["role"] == "assistant": # Target model response
message["content"] = f"{message['content']}" # Highlight with Markdown
return body
🚧 Potential Confusion: Clear FAQ 🛑
Q: How Are Filters Different From Pipe Functions?
Filters modify data going to and coming from models but do not significantly interact with logic outside of these phases. Pipes, on the other hand:
code
Can integrate external APIs or significantly transform how the backend handles operations.
Expose custom logic as entirely new "models."
Q: Can I Do Heavy Post-Processing Inside outlet?
You can, but it’s not the best practice.:
code
Filters are designed to make lightweight changes or apply logging.
If heavy modifications are required, consider a Pipe Function instead.
🎉 Recap: Why Build Filter Functions?
By now, you’ve learned:
code
Inlet manipulates user inputs (pre-processing).
Stream intercepts and modifies streamed model outputs (real-time).
Outlet tweaks AI outputs (post-processing).
Filters are best for lightweight, real-time alterations to the data flow.
With Valves, you empower users to configure Filters dynamically for tailored behavior.
🚀 Your Turn: Start experimenting! What small tweak or context addition could elevate your Open WebUI experience? Filters are fun to build, flexible to use, and can take your models to the next level!
Happy coding! ✨
Assistant
Sure, I'd be happy to help you write a filter function for Open WebUI based on the documentation you provided! Filters are a fantastic way to customize the behavior of your AI interactions, whether you're tweaking inputs for better context or refining outputs for user-friendliness.
Since you didn't specify exactly what your filter should do, I'll start by asking for a bit more detail to make this tailored to your needs. For example:
Do you want to modify user inputs (e.g., add context or clean up text)?
Handle streamed outputs (e.g., remove emojis in real-time)?
Post-process outputs (e.g., format responses or redact sensitive info)?
Add any configurable options via "Valves"?
If you're not sure, I'll provide a simple, practical example based on the documentation: a filter that adds a custom system prompt to every user input. This is a common use case, like in the documentation's Example #1, where we ensure the LLM always knows its role (e.g., "You're a helpful assistant").
I'll walk you through the code step by step, explain how it fits into the Filter structure, and then suggest how you can customize it. Let's get started!
Step 1: Understanding the Filter Structure
From the documentation, a basic Filter class includes:
Valves: A Pydantic model for configuration options (optional, but useful for user-customizable settings).
inlet: Where you modify the input data before it goes to the LLM.
stream: For real-time modifications to streamed outputs (if you're using streaming in Open WebUI 0.5.17+).
outlet: Where you tweak the output after the LLM responds.
We'll focus on a simple inlet function for this example, but I'll include placeholders for stream and outlet so you can expand it later.
Step 2: Writing the Filter Code
Here's a complete, working example of a filter that adds a system prompt to the user's input. This ensures that every conversation starts with a predefined context, like making the LLM act as a "software troubleshooting assistant."
python
from pydantic import BaseModel
from typing import Optional
class Filter:
# Valves: Configuration options for the filter
class Valves(BaseModel):
system_prompt: str = "You're a helpful software troubleshooting assistant." # Default system prompt
def __init__(self):
# Initialize valves with user-configurable options
self.valves = self.Valves()
def inlet(self, body: dict, __user__: Optional[dict] = None) -> dict:
# This function modifies the input before it's sent to the LLM
# Add the system prompt as the first message in the conversation
if "messages" in body:
context_message = {
"role": "system",
"content": self.valves.system_prompt # Use the configurable prompt
}
# Insert the context at the beginning of the messages list
body.setdefault("messages", []).insert(0, context_message)
return body # Return the modified body
def stream(self, event: dict) -> dict:
# This function handles real-time modifications to streamed outputs
# For now, we'll just pass through the event, but you can add logic here
# Example: Remove emojis from streamed content
for choice in event.get("choices", []):
delta = choice.get("delta", {})
if "content" in delta:
# Remove emojis (as in the doc's example)
delta["content"] = delta["content"].replace("😊", "") # Or any other emoji/pattern
return event
def outlet(self, body: dict, __user__: Optional[dict] = None) -> dict: # Note: Doc says -> None, but examples return dict
# This function modifies the output after it's generated
# For example, let's format the assistant's response with Markdown for readability
if "messages" in body:
for message in body["messages"]:
if message.get("role") == "assistant":
# Wrap the content in bold Markdown
message["content"] = f"**{message['content']}**"
return body # Return the modified body
Step 3: Explanation of the Code
Let me break this down based on the key components from the documentation:
Valves (Configuration):
I added a simple configurable option: system_prompt. This is a string that defaults to "You're a helpful software troubleshooting assistant."
Why? This lets users change the prompt via Open WebUI's settings without editing the code. For instance, they could set it to "You're a creative storyteller" when installing the filter.
In the __init__ method, we initialize the Valves object so it's available throughout the filter.
inlet Function:
This is where the magic happens for input modification. It takes the body (the chat request dictionary) and adds a system message at the start of the messages list.
Example: If the user sends a query like "How do I fix this error?", the modified body will include your system prompt first. The LLM will then process it with that context.
Key line: body.setdefault("messages", []).insert(0, context_message). This ensures we're not overwriting existing messages and always add the context at the beginning.
Output: The function returns the modified body, which is then sent to the LLM.
stream Function:
This is for real-time handling of streamed responses (available in Open WebUI 0.5.17+). In this example, I included a basic emoji removal (inspired by the doc's example) to show how you might filter chunks as they arrive.
If you're not using streaming, you can leave this as a pass-through (just return the event unchanged). Otherwise, customize it for tasks like censoring words or logging.
outlet Function:
This processes the full response after the LLM generates it. In this example, I added simple Markdown formatting to make the assistant's responses bold for better readability (e.g., from "Hello!" to "Hello!").
Note: The documentation's skeleton shows -> None, but the examples return a dict, so I made it return body to match the practical use cases. If you're seeing errors, double-check your Open WebUI version.
Step 4: How to Use and Test This Filter
Installation: Save this code in a Python file (e.g., my_filter.py) and place it in the appropriate plugins directory for Open WebUI (check the docs for your setup). Then, enable it in the Open WebUI interface.
Testing:
Send a test query through Open WebUI, like "What should I do if my app crashes?"
With this filter, the LLM should respond as if it's a "software troubleshooting assistant," and the output might look bolded.
Use the Open WebUI logs to verify that the inlet, stream, and outlet functions are being called (e.g., you'll see prints if you add them for debugging).
Step 5: Customization Ideas
Now that you have a base, here are some ways to adapt it based on the documentation:
Add More Valves: If you want users to toggle features, add options like enable_emoji_removal: bool = True in the Valves class. Then, check it in the stream function (e.g., if self.valves.enable_emoji_removal: ...).
Enhance inlet: For cleaning inputs, add code to remove excessive punctuation or emojis from the user's message:
python
if "messages" in body:
last_message = body["messages"][-1] # Get the latest user message
if last_message.get("role") == "user":
last_message["content"] = last_message["content"].replace("!!!", "").strip()
Customize stream: If you're dealing with real-time data, expand it to filter out profanity or log events:
python
def stream(self, event: dict) -> dict:
print(f"Streamed event: {event}") # Log for debugging
# Add more logic here
return event
** outlet for Advanced Output Handling**: If you need to redact sensitive info, use something like the doc's example:
python
def outlet(self, body: dict) -> dict:
for message in body.get("messages", []):
if message.get("role") == "assistant":
message["content"] = message["content"].replace("API_KEY", "[REDACTED]")
return body
Best Practices: Keep things lightweight—filters are meant for quick tweaks, not heavy processing. If you need more complex logic, consider Pipes as mentioned in the FAQ.
Final Thoughts
This should give you a solid starting point! If this example doesn't quite fit what you had in mind, please provide more details (e.g., "I want to remove URLs from outputs" or "Add user-specific context"), and I can refine it further. Filters are super flexible and fun to experiment with—once you get this running, you might find all sorts of ways to enhance your Open WebUI setup.