Doesnt work, the response message is now empty fully. Here's an example of a filter function written by the community, maybe itll help.
code
"""
title: Chat Metrics
author: constLiakos
funding_url: https://github.com/open-webui
version: 0.0.4
license: MIT
changelog:
- 0.0.1 - Initial upload to openwebui community.
- 0.0.2 - format, remove unnecessary code
- 0.0.3 - add advanced stats: tokens & elapsed time
- 0.0.4 - each metric has its enable switch Valve, experimental metrics are disabled by default
"""
from pydantic import BaseModel, Field
from typing import Optional, Callable, Any, Awaitable
import tiktoken
import os
import time
from utils.misc import get_last_assistant_message
def num_tokens_from_string(user_message: str, model_name: str) -> int:
encoding = tiktoken.encoding_for_model(model_name)
print(encoding)
num_tokens = len(encoding.encode(user_message))
return num_tokens
class Filter:
class Valves(BaseModel):
priority: int = Field(
default=5, description="Priority level for the filter operations."
)
elapsed_time: bool = Field(
default=True,
description="Enable for advanced stats",
)
tokens_no: bool = Field(
default=False,
description="Display total Tokens (Experimantal, NOT Accurate)",
)
tokens_per_sec: bool = Field(
default=False,
description="Display Tokens per Second (Experimantal, NOT Accurate)",
)
pass
def __init__(self):
self.valves = self.Valves()
self.start_time = None
pass
def inlet(
self,
body: dict,
):
self.start_time = time.time()
return body
async def outlet(
self,
body: dict,
__event_emitter__: Callable[[Any], Awaitable[None]],
__model__: Optional[dict] = None,
) -> dict:
end_time = time.time()
elapsed_time = end_time - self.start_time
elapsed_time_str = f"Elapsed time: {elapsed_time:.2f} seconds"
response_message = get_last_assistant_message(body["messages"])
# model = __model__["id"]
model = "gpt-4o"
tokens = num_tokens_from_string(response_message, model)
tokens_per_sec = tokens / elapsed_time
stats_array = []
if self.valves.tokens_per_sec:
stats_array.append(f"{tokens_per_sec:.2f} T/s")
if self.valves.tokens_no:
stats_array.append(f"{tokens} tokens")
if self.valves.elapsed_time:
stats_array.append(f"{elapsed_time:.2f} sec")
stats = " | ".join(stat for stat in stats_array)
await __event_emitter__(
{
"type": "status",
"data": {
"description": stats,
"done": True,
},
}
)
return body
Assistant
Ah, this is very helpful! I see the issue now. The community example shows that:
The outlet function should be async
It takes additional parameters like __event_emitter__
It uses a utility function get_last_assistant_message from utils.misc
Let's modify your NanoGPT balance filter based on this example:
python
from pydantic import BaseModel, Field
from typing import Optional, Callable, Any, Awaitable
import requests
from utils.misc import get_last_assistant_message # Import the utility function
class Filter:
class Valves(BaseModel):
api_key: str = Field(
default="YOUR_API_KEY",
description="NanoGPT API Key"
)
priority: int = Field(
default=5,
description="Priority level for the filter operations."
)
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")
return balance_info
except Exception as e:
print(f"Error checking balance: {e}")
return None
def inlet(self, body: dict) -> dict:
return body
def stream(self, event: dict) -> dict:
return event
async def outlet(
self,
body: dict,
__event_emitter__: Callable[[Any], Awaitable[None]],
__model__: Optional[dict] = None
) -> dict:
balance = self.check_balance()
if balance:
# Get the balance info string
balance_info = (
f"💰 NanoGPT Balance: {balance['balance']} Nano | "
f"Receivable: {balance['receivable']} Nano | "
f"Earned: {balance['earned']} Nano"
)
# Emit the balance as a status
await __event_emitter__(
{
"type": "status",
"data": {
"description": balance_info,
"done": True,
},
}
)
return body
Key changes:
Made outlet an async function with the correct parameters
Instead of modifying the message content, we're using __event_emitter__ to show the balance as a status message (like the metrics in the community example)
Added proper Field descriptions in the Valves class
Removed the message modification part since we're using the status approach instead
This should now:
Show the balance as a status message below the chat
Not interfere with the actual message content
Follow the same pattern as the working community filter
Try this version and let me know if it works better! If you still have issues, could you share: