Intercept requests with the before_completion hook
mainThe before_completion hook allows you to modify requests before they reach the AI provider. This is ideal for PII redaction, dynamic model selection, or logging.
Hooks can be configured at three levels, applied in order (Global $\rightarrow$ Class $\rightarrow$ Instance). Later levels override earlier ones for the same parameter.
Hook Return Values:
- Return a Hash of parameters to merge into the request.
- Or, modify the
context.messagesarray directly (e.g., for redaction or adding system prompts).
The CompletionContext Object:
Hooks receive a context object providing access to:
context.messages: The mutable array of messages (OpenAI format).context.params: The mutable hash of request parameters.context.current_model: The currently configured model.context.transcript: The instance's transcript.context.chat_completion: TheChatCompletioninstance.context.configuration: The instance's configuration.
# Global level
Raix.configure do |config|
config.before_completion = ->(context) { { temperature: 0.7 } }
end
# Class level
class MyAssistant
include Raix::ChatCompletion
configure do |config|
config.before_completion = ->(context) { { model: "gpt-4o" } }
end
end
# Instance level
assistant = MyAssistant.new
assistant.before_completion = ->(context) { { max_tokens: 500 } }