Intercept and modify requests and responses in real-time with sandboxed Lua scripts
The Lua Plugin System enables you to intercept and modify requests and responses in real-time using sandboxed Lua scripts. This is the foundation of the Cortex Router intelligent routing engine and enables powerful customization without modifying switchAILocal’s core code.
Plugins run in a sandboxed Lua environment with access to the switchai host API for logging, caching, LLM classification, and intelligent routing features.
return { name = "my-plugin", -- Must match folder name display_name = "My Plugin", -- Human-readable name version = "1.0.0", description = "What this plugin does"}
local Schema = require("schema")local Plugin = {}function Plugin:on_request(req) -- Modify request before it's sent -- req.model, req.body, req.metadata switchai.log("Processing request for: " .. req.model) -- Example: Route based on content local body_str = req.body if string.find(body_str, "code") then req.model = "gpt-4-turbo" end return req -- or nil to skipendfunction Plugin:on_response(res) -- Process response after it's received -- res.body, res.model, res.metadata return res -- or nil to skipendreturn Plugin
local Schema = require("schema")local Plugin = {}function Plugin:on_request(req) switchai.log("[my-plugin] Processing: " .. req.model) -- Example: Inject system prompt for specific models if string.find(req.model, "gpt") then local system_prompt = "You are a helpful assistant." req.body = switchai.json_inject(req.body, system_prompt) end return reqendfunction Plugin:on_response(res) -- Example: Log successful completions if res.metadata and res.metadata.status == 200 then switchai.log("[my-plugin] Success: " .. res.model) end return resendreturn Plugin
function Plugin:on_request(req) local body_str = req.body -- Route coding questions to specialized model if string.find(body_str, "function") or string.find(body_str, "class") or string.find(body_str, "def ") then req.model = "gpt-4-turbo" switchai.log("[router] Detected code, routing to gpt-4-turbo") end -- Route long context to models with large windows if #body_str > 10000 then req.model = "claude-3-opus" switchai.log("[router] Large context, routing to claude-3-opus") end return reqend
function Plugin:on_request(req) -- Extract user from metadata local user = req.metadata["x-user-id"] or "default" -- Route premium users to better models local premium_users = {"user123", "user456"} for _, premium in ipairs(premium_users) do if user == premium then req.model = "gpt-4" switchai.log("[router] Premium user, routing to gpt-4") return req end end -- Standard users get fast model req.model = "gpt-3.5-turbo" return reqend