Documentation
¶
Overview ¶
Package hooks provides synchronous interception points for provider calls, tool execution, and session lifecycle in the PromptKit runtime.
Index ¶
- Constants
- Variables
- func BuildExecHooks(bindings map[string]*execconfig.ExecHook, sandboxes map[string]sandbox.Sandbox) (provider []ProviderHook, tool []ToolHook, session []SessionHook, err error)
- func ResolveSandboxes(specs map[string]*execconfig.SandboxConfig) (map[string]sandbox.Sandbox, error)
- type ChunkInterceptor
- type Decision
- type EmitterAware
- type ExecHookConfig
- type ExecProviderHook
- type ExecSessionHook
- func (h *ExecSessionHook) Name() string
- func (h *ExecSessionHook) OnSessionEnd(ctx context.Context, event SessionEvent) error
- func (h *ExecSessionHook) OnSessionStart(ctx context.Context, event SessionEvent) error
- func (h *ExecSessionHook) OnSessionUpdate(ctx context.Context, event SessionEvent) error
- type ExecToolHook
- type HookDeniedError
- type InputRequest
- type Option
- type OutputRequest
- type ProviderHook
- type ProviderRequest
- type ProviderResponse
- type Registry
- func (r *Registry) HasChunkInterceptors() bool
- func (r *Registry) HasToolResultRewriters() bool
- func (r *Registry) IsEmpty() bool
- func (r *Registry) RunAfterProviderCall(ctx context.Context, req *ProviderRequest, resp *ProviderResponse) Decision
- func (r *Registry) RunAfterToolExecution(ctx context.Context, req ToolRequest, resp ToolResponse) Decision
- func (r *Registry) RunBeforeProviderCall(ctx context.Context, req *ProviderRequest) Decision
- func (r *Registry) RunBeforeToolExecution(ctx context.Context, req ToolRequest) Decision
- func (r *Registry) RunOnChunk(ctx context.Context, chunk *providers.StreamChunk) Decision
- func (r *Registry) RunSessionEnd(ctx context.Context, event SessionEvent) error
- func (r *Registry) RunSessionStart(ctx context.Context, event SessionEvent) error
- func (r *Registry) RunSessionUpdate(ctx context.Context, event SessionEvent) error
- func (r *Registry) RunToolResultRewriters(ctx context.Context, req ToolRequest, content string) (string, error)
- func (r *Registry) SetEmitter(e *events.Emitter)
- type SessionEvent
- type SessionHook
- type ToolHook
- type ToolRequest
- type ToolResponse
- type ToolResultRewriter
Examples ¶
Constants ¶
const ( HookTypeProvider = "provider" HookTypeTool = "tool" HookTypeSession = "session" HookTypeEval = "eval" )
Hook type names as used in execconfig.ExecHook.Hook.
const ( // DirectionInput gates the user's input, in BeforeCall. DirectionInput = "input" // DirectionOutput gates the assistant's response, in AfterCall. DirectionOutput = "output" // DirectionBoth gates input and output. DirectionBoth = "both" )
Guardrail directions: which side of a provider call a check gates, and the vocabulary a firing is tagged with.
Both the guardrail adapter and the pipeline stage use these labels, so they live here rather than in hooks/guardrails.
const MetadataKeyValidatorDeclaration = "validator_declaration"
MetadataKeyValidatorDeclaration is the Decision.Metadata key under which a pack-declared guardrail reports its *packspec.Validator, so the stage can put it on the validation event. The stage removes it before recording the decision on the message.
Variables ¶
var Allow = Decision{Allow: true} //nolint:gochecknoglobals // convenience sentinel
Allow is the zero-cost approval decision.
Functions ¶
func BuildExecHooks ¶
func BuildExecHooks(bindings map[string]*execconfig.ExecHook, sandboxes map[string]sandbox.Sandbox) ( provider []ProviderHook, tool []ToolHook, session []SessionHook, err error)
BuildExecHooks converts runtime-config exec-hook bindings into provider, tool, and session hook instances, resolving each binding's named sandbox from the provided map. Bindings with Hook=="eval" are skipped: eval hooks live in the evals package and are wired by the caller. This is the single source of truth for turning execconfig.ExecHook bindings into runtime hooks, used by both the SDK and Arena so the two never drift.
func ResolveSandboxes ¶
func ResolveSandboxes(specs map[string]*execconfig.SandboxConfig) (map[string]sandbox.Sandbox, error)
ResolveSandboxes builds a map from declared sandbox names to ready Sandbox instances using the process-wide factory registry. Factories must have been registered (via sandbox.RegisterFactory or a backend's init) beforehand. Shared by the SDK and Arena so both resolve sandboxes identically.
Types ¶
type ChunkInterceptor ¶
type ChunkInterceptor interface {
OnChunk(ctx context.Context, chunk *providers.StreamChunk) Decision
}
ChunkInterceptor is an opt-in streaming extension for ProviderHook. ProviderHooks that also implement ChunkInterceptor will have OnChunk called for each streaming chunk, enabling early abort.
type Decision ¶
type Decision struct {
Allow bool
Reason string
Metadata map[string]any
// Enforced indicates the hook already applied enforcement (e.g., truncated
// or replaced content on the response). When true, the provider stage
// records the validation result but continues the pipeline instead of
// returning an error.
Enforced bool
}
Decision is the result of a hook evaluation.
func DenyWithMetadata ¶
DenyWithMetadata creates a denial decision with a reason and metadata.
type EmitterAware ¶
EmitterAware is implemented by hooks that report their own events. A hook cannot build an emitter for itself: the session and conversation IDs the events must carry are only known once the conversation exists, long after hooks are compiled from the pack.
The provider stage constructor holds both the emitter and the hook registry, so it joins the two.
type ExecHookConfig ¶
type ExecHookConfig struct {
Name string
Command string
Args []string
Env []string
TimeoutMs int
Phases []string
Mode string // "filter" | "observe"
Sandbox sandbox.Sandbox
}
ExecHookConfig holds the configuration for creating exec-based hooks.
Sandbox, when non-nil, controls how the hook subprocess is launched. When nil, the exec hooks use the built-in direct sandbox, which runs exec.CommandContext(Command, Args...) in-process with the local environment. SDK consumers that want their hooks to run elsewhere (in a sidecar, a disposable container, a managed cloud sandbox) construct a Sandbox implementation and pass it here.
type ExecProviderHook ¶
type ExecProviderHook struct {
// contains filtered or unexported fields
}
ExecProviderHook implements ProviderHook by spawning an external subprocess.
func NewExecProviderHook ¶
func NewExecProviderHook(cfg *ExecHookConfig) *ExecProviderHook
NewExecProviderHook creates a new ExecProviderHook from the given config.
func (*ExecProviderHook) AfterCall ¶
func (h *ExecProviderHook) AfterCall( ctx context.Context, req *ProviderRequest, resp *ProviderResponse, ) Decision
AfterCall intercepts an LLM provider call after it completes.
func (*ExecProviderHook) BeforeCall ¶
func (h *ExecProviderHook) BeforeCall(ctx context.Context, req *ProviderRequest) Decision
BeforeCall intercepts an LLM provider call before it is sent.
func (*ExecProviderHook) Name ¶
func (h *ExecProviderHook) Name() string
Name returns the hook name.
type ExecSessionHook ¶
type ExecSessionHook struct {
// contains filtered or unexported fields
}
ExecSessionHook implements SessionHook by spawning an external subprocess.
func NewExecSessionHook ¶
func NewExecSessionHook(cfg *ExecHookConfig) *ExecSessionHook
NewExecSessionHook creates a new ExecSessionHook from the given config.
func (*ExecSessionHook) OnSessionEnd ¶
func (h *ExecSessionHook) OnSessionEnd(ctx context.Context, event SessionEvent) error
OnSessionEnd handles the session end event.
func (*ExecSessionHook) OnSessionStart ¶
func (h *ExecSessionHook) OnSessionStart(ctx context.Context, event SessionEvent) error
OnSessionStart handles the session start event.
func (*ExecSessionHook) OnSessionUpdate ¶
func (h *ExecSessionHook) OnSessionUpdate(ctx context.Context, event SessionEvent) error
OnSessionUpdate handles a session update event.
type ExecToolHook ¶
type ExecToolHook struct {
// contains filtered or unexported fields
}
ExecToolHook implements ToolHook by spawning an external subprocess.
func NewExecToolHook ¶
func NewExecToolHook(cfg *ExecHookConfig) *ExecToolHook
NewExecToolHook creates a new ExecToolHook from the given config.
func (*ExecToolHook) AfterExecution ¶
func (h *ExecToolHook) AfterExecution(ctx context.Context, req ToolRequest, resp ToolResponse) Decision
AfterExecution intercepts a tool call after execution.
func (*ExecToolHook) BeforeExecution ¶
func (h *ExecToolHook) BeforeExecution(ctx context.Context, req ToolRequest) Decision
BeforeExecution intercepts a tool call before execution.
type HookDeniedError ¶
type HookDeniedError struct {
HookName string
HookType string // "provider_before" or "provider_after"
Reason string
Metadata map[string]any
}
HookDeniedError is returned when a hook denies an operation.
The provider stage returns it and sets HookName to the fixed string "provider_hook" rather than the denying hook's own Name().
func (*HookDeniedError) Error ¶
func (e *HookDeniedError) Error() string
type InputRequest ¶
type InputRequest struct {
// UserInput is the text of the user message being gated.
UserInput string
// Messages is the full conversation history including that message.
Messages []types.Message
// Round is the provider round this call belongs to (1-based).
Round int
// Replacement supplies the canned assistant text when the check
// returns Enforced. Empty falls back to the default blocked message.
Replacement string
}
InputRequest is the narrow view of an about-to-be-sent call handed to a func-based input guardrail. Use guardrails.InputFunc to build one.
type Option ¶
type Option func(*Registry)
Option configures a Registry during construction.
func WithProviderHook ¶
func WithProviderHook(h ProviderHook) Option
WithProviderHook registers a provider hook.
func WithSessionHook ¶
func WithSessionHook(h SessionHook) Option
WithSessionHook registers a session hook.
type OutputRequest ¶
type OutputRequest struct {
// Content is the assistant text being gated.
Content string
// Message is the response message; mutate it in place to enforce.
Message *types.Message
// Round is the provider round this response belongs to (1-based).
Round int
}
OutputRequest is the narrow view of a completed call handed to a func-based output guardrail. Use guardrails.OutputFunc to build one.
type ProviderHook ¶
type ProviderHook interface {
Name() string
BeforeCall(ctx context.Context, req *ProviderRequest) Decision
AfterCall(ctx context.Context, req *ProviderRequest, resp *ProviderResponse) Decision
}
ProviderHook intercepts LLM provider calls.
type ProviderRequest ¶
type ProviderRequest struct {
ProviderID string
Model string
Messages []types.Message
SystemPrompt string
Round int
Metadata map[string]any
// TurnIndex is the 0-based turn this call belongs to, counted by the
// ProviderStage. Round is not a substitute: it counts tool-loop rounds
// within one turn and restarts in each composition sub-pipeline.
TurnIndex int
// Prompt is the pack's definition of the prompt the model is being
// invoked for, a read-only copy taken when the conversation was built.
// After a workflow handoff it is the destination state's prompt. Nil means
// undeclared. PromptKit never reads it.
Prompt *packspec.Prompt
// Replacement is written by a BeforeCall hook that returns Enforced, to
// supply the assistant text returned in place of the blocked provider
// call. Mirrors how output guardrails mutate resp.Message in AfterCall.
// Empty falls back to Decision.Metadata["replacement"], then to
// prompt.DefaultBlockedMessage.
Replacement string
}
ProviderRequest describes an LLM call about to be made.
type ProviderResponse ¶
type ProviderResponse struct {
ProviderID string
Model string
Message types.Message
Round int
LatencyMs int64
}
ProviderResponse describes a completed LLM call.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds registered hooks and provides chain-execution methods. A nil *Registry is safe to use: all Run* methods return Allow / nil.
func NewRegistry ¶
NewRegistry creates a Registry with the given options.
func (*Registry) HasChunkInterceptors ¶
HasChunkInterceptors returns true if any registered provider hook implements ChunkInterceptor.
func (*Registry) HasToolResultRewriters ¶ added in v2.17.0
HasToolResultRewriters reports whether any tool hook rewrites results.
func (*Registry) RunAfterProviderCall ¶
func (r *Registry) RunAfterProviderCall(ctx context.Context, req *ProviderRequest, resp *ProviderResponse) Decision
RunAfterProviderCall executes all provider hooks' AfterCall in order. The first non-Allow decision wins and short-circuits.
func (*Registry) RunAfterToolExecution ¶
func (r *Registry) RunAfterToolExecution(ctx context.Context, req ToolRequest, resp ToolResponse) Decision
RunAfterToolExecution executes all tool hooks' AfterExecution in order. First deny wins and short-circuits.
func (*Registry) RunBeforeProviderCall ¶
func (r *Registry) RunBeforeProviderCall(ctx context.Context, req *ProviderRequest) Decision
RunBeforeProviderCall executes all provider hooks' BeforeCall in order. The first non-Allow decision wins and short-circuits.
Example ¶
ExampleRegistry_RunBeforeProviderCall shows registering a ProviderHook and running it before an LLM call. Hooks run in registration order; the first denial short-circuits the chain and its Decision is returned.
package main
import (
"context"
"fmt"
"github.com/AltairaLabs/PromptKit/runtime/v2/hooks"
)
// modelDenylist is a minimal hooks.ProviderHook that blocks calls to a
// specific model. Real hooks (e.g. runtime/hooks/guardrails) do content
// moderation, PII redaction, and similar — this shows the shape any
// ProviderHook implementation takes.
type modelDenylist struct {
banned string
}
func (d modelDenylist) Name() string { return "model-denylist" }
func (d modelDenylist) BeforeCall(_ context.Context, req *hooks.ProviderRequest) hooks.Decision {
if req.Model == d.banned {
return hooks.Deny("model is not allowed")
}
return hooks.Allow
}
func (d modelDenylist) AfterCall(_ context.Context, _ *hooks.ProviderRequest, _ *hooks.ProviderResponse) hooks.Decision {
return hooks.Allow
}
// ExampleRegistry_RunBeforeProviderCall shows registering a ProviderHook and
// running it before an LLM call. Hooks run in registration order; the first
// denial short-circuits the chain and its Decision is returned.
func main() {
reg := hooks.NewRegistry(hooks.WithProviderHook(modelDenylist{banned: "banned-model"}))
decision := reg.RunBeforeProviderCall(context.Background(), &hooks.ProviderRequest{Model: "banned-model"})
fmt.Println(decision.Allow, decision.Reason)
}
Output: false model is not allowed
func (*Registry) RunBeforeToolExecution ¶
func (r *Registry) RunBeforeToolExecution(ctx context.Context, req ToolRequest) Decision
RunBeforeToolExecution executes all tool hooks' BeforeExecution in order. First deny wins and short-circuits.
func (*Registry) RunOnChunk ¶
RunOnChunk executes all chunk interceptors in order. First deny wins and short-circuits.
func (*Registry) RunSessionEnd ¶
func (r *Registry) RunSessionEnd(ctx context.Context, event SessionEvent) error
RunSessionEnd executes every session hook's OnSessionEnd in order. See runSessionHooks for how failures are handled.
func (*Registry) RunSessionStart ¶
func (r *Registry) RunSessionStart(ctx context.Context, event SessionEvent) error
RunSessionStart executes every session hook's OnSessionStart in order. See runSessionHooks for how failures are handled.
func (*Registry) RunSessionUpdate ¶
func (r *Registry) RunSessionUpdate(ctx context.Context, event SessionEvent) error
RunSessionUpdate executes every session hook's OnSessionUpdate in order. See runSessionHooks for how failures are handled.
func (*Registry) RunToolResultRewriters ¶ added in v2.17.0
func (r *Registry) RunToolResultRewriters(ctx context.Context, req ToolRequest, content string) (string, error)
RunToolResultRewriters passes a tool result's text through every tool hook that implements ToolResultRewriter, in order. The first error stops the chain and is returned.
func (*Registry) SetEmitter ¶
SetEmitter hands the emitter to every registered provider hook that wants one. Hooks that do not implement EmitterAware are untouched. Nil-safe on both the receiver and the emitter.
type SessionEvent ¶
type SessionEvent struct {
SessionID string
ConversationID string
Messages []types.Message
TurnIndex int
Metadata map[string]any
}
SessionEvent carries context for session lifecycle hooks.
type SessionHook ¶
type SessionHook interface {
Name() string
OnSessionStart(ctx context.Context, event SessionEvent) error
OnSessionUpdate(ctx context.Context, event SessionEvent) error
OnSessionEnd(ctx context.Context, event SessionEvent) error
}
SessionHook tracks session lifecycle.
type ToolHook ¶
type ToolHook interface {
Name() string
BeforeExecution(ctx context.Context, req ToolRequest) Decision
AfterExecution(ctx context.Context, req ToolRequest, resp ToolResponse) Decision
}
ToolHook intercepts tool execution (LLM-initiated calls only).
type ToolRequest ¶
type ToolRequest struct {
Name string
Args json.RawMessage
CallID string
// Declaration is the pack's definition of the tool, the same value its
// executor receives on tools.ToolDescriptor.Declaration, so a host that
// only allows or denies needs one hook covering every tool. Nil means the
// pack does not declare the tool. PromptKit never reads it.
Declaration *packspec.Tool
}
ToolRequest describes a tool call about to be executed.
type ToolResponse ¶
ToolResponse describes a completed tool execution.
type ToolResultRewriter ¶ added in v2.17.0
type ToolResultRewriter interface {
RewriteResult(ctx context.Context, req ToolRequest, content string) (string, error)
}
ToolResultRewriter is an opt-in extension for ToolHook. A ToolHook that also implements it may rewrite the text of a tool's successful result before the model sees it, as a test harness does to plant an indirect prompt injection in live tool output.
The provider stage calls it for the tools it runs: once with a plain result's text, or once per text part of a multimodal result, before the result size limit applies. Rewriters run in registration order, each on the previous one's output; an error fails the tool call. Client tools, calls resumed after approval and duplex sessions are not rewritten. Parallel tool calls rewrite concurrently, so RewriteResult must be safe for concurrent use.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package execconfig holds the declarative shape of exec-hook, exec-eval and sandbox bindings.
|
Package execconfig holds the declarative shape of exec-hook, exec-eval and sandbox bindings. |
|
Package guardrails provides built-in ProviderHook implementations that bridge the unified eval system to the pipeline's hook infrastructure.
|
Package guardrails provides built-in ProviderHook implementations that bridge the unified eval system to the pipeline's hook infrastructure. |
|
Package sandbox defines the Sandbox interface used by exec-backed hooks to externalize where and how the hook subprocess is spawned.
|
Package sandbox defines the Sandbox interface used by exec-backed hooks to externalize where and how the hook subprocess is spawned. |
|
direct
Package direct provides the default Sandbox implementation for exec hooks: it spawns the command as a local subprocess via exec.CommandContext.
|
Package direct provides the default Sandbox implementation for exec hooks: it spawns the command as a local subprocess via exec.CommandContext. |