Skip to main content

Custom callbacks

A custom callback is your own Python code that the gateway runs for every request. Use one when no built-in integration fits, for example to write usage rows into an internal billing table, to post failures to a chat room of your own, or to inspect and change requests before they reach a model. A custom callback is a class that subclasses CustomLogger and overrides only the methods you care about.

A real-world scenario​

A company charges each internal product for its model usage through an internal billing service that no observability platform knows about. The platform team writes a 30 line callback that, after every successful call, posts the key alias, team, model, tokens and cost to that service. They drop the file next to the gateway's config, name it in callbacks, restart, and from then on every request through the gateway is billed without any application change.

Write the callback​

from spanway.integrations.custom_logger import CustomLogger


class AuditLogger(CustomLogger):
def log_pre_api_call(self, model, messages, kwargs):
print("calling", model)

async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
usage = response_obj.usage
cost = kwargs.get("response_cost")
metadata = kwargs.get("spanway_params", {}).get("metadata", {})
print("ok", kwargs["model"], usage.total_tokens, cost, metadata.get("user_api_key_alias"))

async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
print("failed", kwargs["model"], kwargs.get("exception"))


audit_logger = AuditLogger()
MethodWhen it runs
log_pre_api_call(model, messages, kwargs)Before the provider call.
log_post_api_call(kwargs, response_obj, start_time, end_time)After the provider returns, before post-processing.
log_success_event, async_log_success_eventAfter a successful call, with the full response and usage.
log_failure_event, async_log_failure_eventAfter a failed call, with the exception in kwargs["exception"].

kwargs contains the request parameters, response_cost, and spanway_params, whose metadata carries the key alias, user and team information on the gateway. Streaming responses are assembled into one response object before the success event fires.

Gateway hooks​

On the gateway the same class can implement request lifecycle hooks.

HookUse
async_pre_call_hook(user_api_key_dict, cache, data, call_type)Inspect or rewrite the request, or raise to reject it.
async_moderation_hook(data, user_api_key_dict, call_type)Runs in parallel with the model call.
async_post_call_success_hook(data, user_api_key_dict, response)Inspect or rewrite the response.
async_post_call_streaming_hook(user_api_key_dict, response)Inspect each streamed chunk.
async_post_call_failure_hook(request_data, original_exception, user_api_key_dict)React to failures.

Run it on the gateway​

  1. Save the class in a file next to config.yaml, for example custom_callbacks.py, and make sure the file defines the instance, here audit_logger.

  2. Reference the instance as module.attribute in the config file. Any entry with a dot in callbacks, success_callback or failure_callback is imported this way. Use success_callback or failure_callback instead of callbacks to run it for one outcome only.

    spanway_settings:
    callbacks: ["custom_callbacks.audit_logger"]
  3. Restart the gateway. A callback under callbacks prints no startup line at the default log level (only Initialized Callbacks - [...] at DEBUG), so confirm it loaded with step 5.

  4. Send one request and watch the gateway's output:

    curl -X POST http://localhost:4000/v1/chat/completions \
    -H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
    -d '{"model": "claude-haiku-5-5", "messages": [{"role": "user", "content": "Hi"}]}'

    Expected result: the response is a normal chat completion, and the gateway's output shows calling claude-haiku-5-5 before the call and ok claude-haiku-5-5 <tokens> <cost> <key alias> after it.

  5. Confirm the callback is active from the API or the Admin UI. GET /callbacks/list names it under success_and_failure, and on Settings, then Logging & Alerts, it appears in Active Logging Callbacks marked Read only, because it was set in the config file.

Tips​

Keep callbacks fast and never raise from a logging method, because an exception there is logged and otherwise ignored, while an exception in a pre-call hook rejects the request. For data you want in the gateway's own spend logs, add it to the request metadata instead of a callback. A callback that needs audit rows implements async_log_audit_log_event and is named in audit_log_callbacks, see audit logs.

Errors​

StatusWhereMeaningFix
Gateway fails to start with an import error naming your moduleGateway startThe file is not on the Python path, or the attribute name is wrong.Put the file next to config.yaml and check module.attribute matches the file name and the instance name.
400 or 500 returned to the client from a pre-call hookAny requestYour async_pre_call_hook raised. The gateway passes the exception to the client, which is how a hook rejects a request.Raise an HTTPException with the status you want, and catch everything else inside the hook.
Callback never runsAny requestIt is not in GET /callbacks/list, usually because the config entry has no dot and was treated as a built-in name.Use the module.attribute form.

Logs​

LevelLineMeaning
ERRORSpanway.LoggingError: [Non-Blocking] Exception occurred while success logging <traceback>A logging method raised. The request was unaffected, and the traceback points at the line in your callback.
ERRORSpanway.LoggingError: [Non-Blocking] Exception occurred in async_logging_hook <traceback>A hook raised while the response was being logged. The request was unaffected.