Okay, that's a classic debugging scenario: the background process works (the API call and logging show success), but the visible output doesn't change.
This usually indicates one of a few things:
- The
body object in outlet isn't what's directly used for rendering: While the docs say outlet modifies the data before showing, there might be another layer or process that doesn't pick up changes made within the outlet function's scope in the way we expect. (Less likely, but possible).
- The modification is happening, but something else is overwriting it: Another filter, or perhaps Open WebUI's internal processing, is somehow overriding the change you make to
message["content"].
- The
body structure is different than expected: Maybe the structure of the body passed to outlet doesn't consistently have the messages list or the role/content keys in the way the code assumes. (Less likely given the examples).
- The
outlet function's return value isn't being used: The documentation skeleton shows -> None, while the examples show return body. Your code does return body, which is correct based on the examples, but it's a point of potential confusion.
Let's add some debugging prints to your outlet function to see exactly what the body looks like before and after you modify it. This will tell us if the modification is even happening within the filter's scope.
from pydantic import BaseModel
from typing import Optional
import requests
import json # Import json for pretty printing
class Filter:
class Valves(BaseModel):
api_key: str = "YOUR_API_KEY" # Make sure this is set in the UI
def __init__(self):
self.valves = self.Valves()
self.NANOGPT_API_BASE_URL = 'https://nano-gpt.com/api/'
self.NANOGPT_API_BALANCE = self.NANOGPT_API_BASE_URL + 'check-nano-balance'
def check_balance(self) -> Optional[dict]:
print("Checking NanoGPT balance...")
try:
headers = {
"x-api-key": self.valves.api_key,
"Content-Type": "application/json"
}
response = requests.post(self.NANOGPT_API_BALANCE, headers=headers)
response.raise_for_status()
balance_info = response.json()
print(f"Balance: {balance_info['balance']} Nano")
print(f"Receivable: {balance_info['receivable']} Nano")
print(f"Earned: {balance_info['earned']} Nano")
return balance_info
except requests.RequestException as e:
print(f"Error checking balance: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f"Response status code: {e.response.status_code}")
try:
print(f"Response content: {e.response.text}")
except Exception as ex:
print(f"Error printing response content: {ex}")
return None
except json.JSONDecodeError as e:
print(f"Error decoding JSON response: {e}")
if hasattr(response, 'text'):
print(f"Response text: {response.text}")
return None
except Exception as e: # Catch any other unexpected errors
print(f"An unexpected error occurred during balance check: {e}")
return None
def inlet(self, body: dict, __user__: Optional[dict] = None) -> dict:
return body
def stream(self, event: dict) -> dict:
return event
def outlet(self, body: dict, __user__: Optional[dict] = None) -> dict:
print("--- Outlet function called ---")
# Print the body *before* modification to understand its structure
print("Body BEFORE modification:")
# Use json.dumps for cleaner dictionary printing
print(json.dumps(body, indent=2))
# Get the balance
balance = self.check_balance()
# If checking balance fails, we won't modify anything
if balance:
# Find the last assistant message
found_assistant_message = False
for message in reversed(body.get("messages", [])):
if message.get("role") == "assistant":
found_assistant_message = True
# Append the balance info to the content
message["content"] += f"\n\n**NanoGPT Balance:**\n"
message["content"] += f"- Balance: {balance['balance']} Nano\n"
message["content"] += f"- Receivable: {balance['receivable']} Nano\n"
message["content"] += f"- Earned: {balance['earned']} Nano\n"
print(f"Appended balance to assistant message with ID: {message.get('id', 'N/A')}") # Log which message was modified
break # Exit the loop after modifying the last assistant message
if not found_assistant_message:
print("No assistant message found in body to append balance.")
# Print the body *after* modification to see if the change took place
print("Body AFTER modification:")
print(json.dumps(body, indent=2))
print("--- Outlet function finished ---")
# Crucially, return the modified body
return body
Instructions:
- Replace the existing filter code with this version.
- Make sure the API key is correctly configured in the filter settings within Open WebUI (not just in the code file).
- Send a message in the chat.
- Observe the console/terminal where your Open WebUI server is running.
What to Look For in the Console Output:
- You should see the "--- Outlet function called ---" and "--- Outlet function finished ---" markers.
- Look at the "Body BEFORE modification:" output. Does it contain a
"messages" list? Does the last message in that list (or the message just before the new assistant message if it's not fully built yet) have "role": "assistant" and a "content" key?
- If an assistant message was found, you should see the "Appended balance to assistant message..." log.
- Look at the "Body AFTER modification:" output. Compare the
content of the last assistant message here with the "Body BEFORE modification:" output. Does the balance text appear in the content string in the AFTER output?
If the balance text IS present in the "Body AFTER modification:" output in the console logs, but NOT visible in the Open WebUI chat interface:
This strongly suggests that Open WebUI's front-end rendering process isn't fully utilizing the body dictionary returned by the outlet filter for the final message display. This could be due to how streamed responses are handled, caching, or a specific UI implementation detail.
In this case, a Filter might not be the ideal place for this type of persistent UI element. You might need to explore:
- Custom Frontend Modifications: If you're comfortable with web development, you might need to modify the Open WebUI front-end code itself to add a dedicated balance display area.
- Pipe Functions: Although the documentation advises against heavy post-processing in
outlet, you could potentially create a simple Pipe function that only calls the balance check API and returns the balance information. You would then need to figure out how to trigger that specific pipe after each chat completion and display its output in the UI. This would likely be complex.
Let's start by checking the debug output from the outlet function. That will confirm whether the modification is occurring server-side within the filter's scope.