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 BlockMessager
- type ChunkInterceptor
- type ChunkJudgment
- type ChunkRequest
- type ChunkRequestInterceptor
- 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 PartialReply
- type ProviderHook
- type ProviderRequest
- type ProviderResponse
- type Registry
- func (r *Registry) BlockMessages() []string
- func (r *Registry) HasChunkInterceptors() bool
- func (r *Registry) HasProviderHooks() bool
- func (r *Registry) HasToolResultRewriters() bool
- func (r *Registry) IsEmpty() bool
- func (r *Registry) JudgeChunk(ctx context.Context, req ChunkRequest) ChunkJudgment
- 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) RunOnChunkRequest(ctx context.Context, req ChunkRequest) 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)
- func (r *Registry) StreamHolders() []StreamHolder
- type SessionEvent
- type SessionHook
- type StreamHoldMode
- type StreamHolder
- 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 ( // MetadataKeySegmentIndex is the 1-based index of the last segment the // judged text covered. MetadataKeySegmentIndex = "segment_index" // MetadataKeySegmentEnd is the byte offset in the round's reply text // where the judged text ended. MetadataKeySegmentEnd = "segment_end" )
Decision.Metadata keys a firing on a partial reply carries, placing it in the streamed reply.
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 BlockMessager ¶ added in v2.22.0
type BlockMessager interface {
BlockMessages() []string
}
BlockMessager is an optional ProviderHook interface for a hook that knows, before it fires, the messages it replaces a blocked turn with. A voice pipeline renders them as speech at session start, so the caller hears one without waiting.
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 ChunkJudgment ¶ added in v2.22.0
type ChunkJudgment struct {
// Firings are the decisions of the interceptors that did not allow the
// chunk, in order: every one is a guardrail firing to record. Each
// enforcing one carries the text it left in Content. A deny ends the
// list: no interceptor runs after it.
Firings []Decision
// Holds, when nothing fired, is each interceptor's Decision.Hold, in
// registration order: how many bytes at the end of the chunk's Content it
// has not cleared.
Holds []int
}
ChunkJudgment is what the chunk interceptors decided about one chunk (Registry.JudgeChunk).
func (ChunkJudgment) MaxHold ¶ added in v2.22.0
func (j ChunkJudgment) MaxHold() int
MaxHold is the most any interceptor holds back (Holds).
type ChunkRequest ¶ added in v2.22.0
type ChunkRequest struct {
// Chunk is the chunk being judged. An interceptor that returns Enforced
// gives the text it leaves in Decision.Content, or rewrites Chunk.Content
// in place, as OnChunk does.
Chunk *providers.StreamChunk
// Caller is who the conversation acts for, as the host set it with
// sdk.WithCaller. The zero value means none was set. PromptKit hands it to
// the host's interceptor and otherwise never reads, persists, logs or
// emits it.
Caller types.Caller
// TurnIndex is the 0-based turn the chunk's reply belongs to, as
// ProviderRequest.TurnIndex counts it.
TurnIndex int
}
ChunkRequest is a streamed response chunk handed to a ChunkRequestInterceptor, with who the call acts for.
type ChunkRequestInterceptor ¶ added in v2.22.0
type ChunkRequestInterceptor interface {
InterceptChunk(ctx context.Context, req ChunkRequest) Decision
}
ChunkRequestInterceptor is ChunkInterceptor with the caller: a ProviderHook that implements it has InterceptChunk called for each streaming chunk, in place of OnChunk when it implements both, so a per-tenant output check sees who the turn acts for.
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
// Hold is set by a chunk interceptor that allows a chunk: how many bytes
// at the end of the chunk's Content it has not cleared yet, because they
// could be the start of content it blocks once more of the reply arrives
// (a banned word split across chunks). The provider stage keeps those
// bytes from the caller until a later chunk clears them, completes what it
// blocks, or the reply ends. Zero holds nothing back.
Hold int
// Content is set by an output hook (AfterCall or a chunk interceptor)
// that returns Enforced: the text its enforcement leaves in place of the
// text it judged, a truncation's prefix or a replacement. A hook that sets
// it need not rewrite the chunk or message it was given. When it is nil,
// the Registry reads what the hook rewrote in place instead, so a hook
// written either way works.
Content *string
}
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.
The hook's stdin is the JSON of the request or event it handles, the conversation's caller (types.Caller, under "Caller") included: an exec hook is host policy code run out of process, so it gets the caller as an in-process hook does. A Sandbox that runs the hook remotely carries the caller there.
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
// Caller is who the conversation acts for, as the host set it with
// sdk.WithCaller. The zero value means none was set.
Caller types.Caller
}
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
// Caller is who the conversation acts for, as the host set it with
// sdk.WithCaller. The zero value means none was set.
Caller types.Caller
}
OutputRequest is the narrow view of a completed call handed to a func-based output guardrail. Use guardrails.OutputFunc to build one.
type PartialReply ¶ added in v2.22.0
type PartialReply struct {
// Text is the round's reply up to the end of the last segment judged.
Text string
// SegmentIndex is the 1-based index of that segment.
SegmentIndex int
// Timeout is the host's bound on the judgment; a hook may set its own.
Timeout time.Duration
}
PartialReply is a streamed reply's text so far, judged by a StreamHolder.
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: 0 for the
// conversation's first turn, on the text path (Send, Stream) and the
// realtime path alike, counted from the persisted transcript. A text
// pipeline built without a state store (sdk.Open always has one) has no
// transcript to count, and reports 0 on every turn. 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
// Caller is who the conversation acts for, as the host set it with
// sdk.WithCaller. The zero value means none was set. PromptKit hands it to
// the host's provider hooks, guardrails included, and otherwise never
// reads, persists, logs or emits it.
Caller types.Caller
}
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) BlockMessages ¶ added in v2.22.0
BlockMessages collects the messages of the provider hooks that implement BlockMessager, each once, in registration order. Messages a hook decides only when it fires are not among them.
func (*Registry) HasChunkInterceptors ¶
HasChunkInterceptors returns true if any registered provider hook implements ChunkInterceptor or ChunkRequestInterceptor.
func (*Registry) HasProviderHooks ¶ added in v2.18.0
HasProviderHooks reports whether any provider hook is registered.
func (*Registry) HasToolResultRewriters ¶ added in v2.17.0
HasToolResultRewriters reports whether any tool hook rewrites results.
func (*Registry) JudgeChunk ¶ added in v2.22.0
func (r *Registry) JudgeChunk(ctx context.Context, req ChunkRequest) ChunkJudgment
JudgeChunk runs every chunk interceptor on req.Chunk and reports each one's decision, without changing req.Chunk: each interceptor is given its own copy.
Every interceptor judges every chunk. One that enforces leaves its text (Decision.Content, or what it rewrote its copy to; a truncation or a replacement), and the interceptors after it judge that text, so a truncation cannot pass on text a later interceptor blocks. A deny (not enforced) ends the chain.
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. It is RunOnChunkRequest for a chunk with no caller.
func (*Registry) RunOnChunkRequest ¶ added in v2.22.0
func (r *Registry) RunOnChunkRequest(ctx context.Context, req ChunkRequest) Decision
RunOnChunkRequest executes all chunk interceptors in order: InterceptChunk for one that implements ChunkRequestInterceptor, OnChunk otherwise. It is JudgeChunk reduced to one decision, for callers that want the chunk rewritten in place.
The decision returned is the last firing (ChunkJudgment.Firings): the deny that stopped the chain, or else the last enforcing interceptor, whose Content stands and is written to req.Chunk.Content. When every interceptor allows the chunk, the decision holds back the most any of them holds (Decision.Hold).
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.
func (*Registry) StreamHolders ¶ added in v2.22.0
func (r *Registry) StreamHolders() []StreamHolder
StreamHolders returns the provider hooks that hold a streamed reply past the tail their chunk check holds (StreamHoldSegment, StreamHoldTurn), in registration order.
type SessionEvent ¶
type SessionEvent struct {
SessionID string
ConversationID string
Messages []types.Message
TurnIndex int
Metadata map[string]any
// Caller is who the conversation acts for, as the host set it with
// sdk.WithCaller. The zero value means none was set. PromptKit hands it to
// the host's session hooks, an exec hook included (as "Caller" in its stdin
// JSON), and otherwise never reads, persists, logs or emits it.
Caller types.Caller
}
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 StreamHoldMode ¶ added in v2.22.0
type StreamHoldMode string
StreamHoldMode is how much of a streamed reply an output guardrail holds back from the caller until it has judged it (the guardrail's stream_hold param). Text the caller receives has passed every guardrail whose mode holds it.
const ( // StreamHoldNone holds nothing: text reaches the caller as it arrives, and // the guardrail judges the completed reply. When it fails that reply, its // message follows the streamed text, marked as replacing it. StreamHoldNone StreamHoldMode = "none" // StreamHoldTail holds the end of the reply that could be the start of // something the guardrail's chunk check blocks (Decision.Hold). StreamHoldTail StreamHoldMode = "tail" // StreamHoldSegment holds every byte not yet in a segment the guardrail // has passed (StreamHolder.JudgePartialReply). Segments are judged while // the model writes on; the last is judged with the completed reply. StreamHoldSegment StreamHoldMode = "segment" // StreamHoldTurn holds the whole reply until the guardrail passes the // completed reply. StreamHoldTurn StreamHoldMode = "turn" )
type StreamHolder ¶ added in v2.22.0
type StreamHolder interface {
// StreamHold is how much of a streamed reply the hook holds back.
StreamHold() StreamHoldMode
// JudgePartialReply judges reply.Text, the reply to req so far, while it
// streams (StreamHoldSegment): the stage calls it as segments become
// ready, at most once at a time per hook, concurrently with the model
// writing the rest, and cancels ctx when the reply is cut or the round
// ends. The earlier text is context: only what is new needs a verdict. A
// judgment that errors or runs out of time fails closed. An Enforced
// decision carries the text that replaces the reply in Content.
JudgePartialReply(ctx context.Context, req *ProviderRequest, reply PartialReply) Decision
}
StreamHolder is implemented by an output provider hook that can hold a streamed reply back from the caller until it has judged it. The provider stage asks it how much it holds once per round. A StreamHoldTail or StreamHoldNone holder holds what its chunk check says (Decision.Hold), as a hook that does not implement this does.
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
// Caller is who the conversation acts for, as the host set it with
// sdk.WithCaller. The zero value means none was set. PromptKit hands it to
// the host's tool hooks, an exec hook included (as "Caller" in its stdin
// JSON), and otherwise never reads, persists, logs or emits it.
Caller types.Caller
}
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, on text turns and realtime duplex sessions alike. Rewriters run in registration order, each on the previous one's output; an error fails the tool call. The SDK also runs it on the results a host settles outside the turn and delivers with Continue, ContinueDuplex or Resume (an approved call, a client tool's answer), with the request the stage would give for the call (an approval with edits gives the edited arguments), and the history keeps the rewritten result. On Resume it runs on the client's answer as sent, which is not formatted or truncated, and what is replayed from the history (to AG-UI, say) is the rewritten text. Parallel tool calls rewrite concurrently, so RewriteResult must be safe for concurrent use.
Source Files
¶
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. |