Documentation
¶
Index ¶
- Variables
- func BuildGenerateOptions(opts ...GenerationOption) []core.GenerateOption
- func GenerateStruct[T any](ctx context.Context, gen core.TextGenerator, sysPrompt string, userReq string) (T, error)
- func GetGenkit(ctx context.Context) *genkit.Genkit
- func InitMiddlewarePlugin(ctx context.Context, g *genkit.Genkit) error
- func IsCallerFailure(err error) bool
- func IsInfraFailure(err error) bool
- func NewGenkitAction(ctx context.Context, modelName string) (core.Action, error)
- func NewGenkitAdapter(model ai.Model, gk *genkit.Genkit) core.TextGenerator
- func WithCustomMiddleware(mw ...ai.Middleware) core.GenerateOption
- func WithFallback(modelRefs []ai.ModelRef) core.GenerateOption
- func WithFilesystem(rootDir string, allowWrite bool) core.GenerateOption
- func WithMiddleware(cfg *MiddlewareConfig) core.GenerateOption
- func WithRetry(maxRetries int) core.GenerateOption
- func WithRetryAndBackoff(maxRetries, initialDelayMs, maxDelayMs int) core.GenerateOption
- func WithToolApproval(allowedTools []string) core.GenerateOption
- type DatalogValidator
- type Example
- type GenerationOption
- func WithDatalogValidator(...) GenerationOption
- func WithFallbackMiddleware(models ...ai.ModelRef) GenerationOption
- func WithFilesystemMiddleware(rootDir string, allowWrite bool) GenerationOption
- func WithGenerationConfig(cfg *core.GenerationConfig) GenerationOption
- func WithLogging(logger core.Logger) GenerationOption
- func WithRetryMiddleware(maxRetries int) GenerationOption
- func WithTelemetry(...) GenerationOption
- func WithToolApprovalMiddleware(allowedTools ...string) GenerationOption
- type GenerationSettings
- type GenkitTextGenerator
- type LLMAction
- func (a *LLMAction) Complete(ctx context.Context, prompt string) (string, error)
- func (a *LLMAction) Execute(ctx context.Context, input core.Envelope) (core.Envelope, error)
- func (a *LLMAction) Generate(ctx context.Context, prompt string, opts ...core.GenerateOption) (*core.LLMResponse, error)
- func (a *LLMAction) Metadata() core.ActionMetadata
- func (a *LLMAction) Stream(ctx context.Context, prompt string) (<-chan core.StreamChunk, error)
- type LoggingMiddleware
- type MiddlewareConfig
- type StreamingGate
- type StreamingSupervisedAction
- func (a *StreamingSupervisedAction) Execute(ctx context.Context, input core.Envelope) (core.Envelope, error)
- func (a *StreamingSupervisedAction) FinalEnvelope() (core.Envelope, bool)
- func (a *StreamingSupervisedAction) Metadata() core.ActionMetadata
- func (a *StreamingSupervisedAction) Stream(ctx context.Context, input core.Envelope) (<-chan core.StreamChunk, error)
- type TelemetryMiddleware
Constants ¶
This section is empty.
Variables ¶
var ErrModelBlocked = ai.ErrGenerationBlocked
ErrModelBlocked re-exports Genkit's safety-refusal sentinel so callers can branch on "the provider refused" without importing Genkit. The value is the same sentinel, so errors.Is works either way.
A refusal is NOT a schema mismatch: retrying the same prompt reproduces it. Genkit used to surface it as an output-validation failure, which made verify-retry loops burn attempts on a model that had already said no.
Functions ¶
func BuildGenerateOptions ¶
func BuildGenerateOptions(opts ...GenerationOption) []core.GenerateOption
BuildGenerateOptions converts GenerationSettings to core.GenerateOption slice.
func GenerateStruct ¶
func GetGenkit ¶
GetGenkit returns the global Genkit instance, initializing it if necessary. This allows other packages to register models/tools.
func InitMiddlewarePlugin ¶
InitMiddlewarePlugin registers the middleware plugin with the Genkit instance. This enables middleware to be visible in the Dev UI.
func IsCallerFailure ¶ added in v0.11.0
IsCallerFailure reports whether err was caused by the request rather than by an unhealthy provider — a bad prompt, an unknown model, a rejected credential, or a safety refusal.
Use it to keep retry and circuit-breaking honest: an uncapped "count every error" policy lets a caller-side mistake (which retries cannot fix) open a circuit breaker and mask a real outage.
Deliberately NOT caller-side: DEADLINE_EXCEEDED and CANCELLED count as infrastructure failures. A caller-imposed short timeout would arguably be the caller's fault, but in practice a deadline at a model boundary means the provider was slow, and treating it as healthy would keep hammering it.
Unclassified errors report false: the safe default is to treat them as infrastructure failures and keep counting them.
func IsInfraFailure ¶ added in v0.11.0
IsInfraFailure reports whether err should count against provider health (outage, throttling, timeout, internal error, or an unknown failure). It is the negation of IsCallerFailure and is the default predicate a circuit breaker should use.
func NewGenkitAction ¶
NewGenkitAction creates a new core.Action backed by a Genkit model. It ensures the Genkit runtime is initialized and looks up the model by name.
func NewGenkitAdapter ¶
NewGenkitAdapter creates a new adapter from a pre-initialized Genkit model.
Parameters:
- model: The Genkit model instance.
- gk: The Genkit runtime instance.
Returns:
- A core.TextGenerator implementation (also satisfies GenkitTextGenerator).
func WithCustomMiddleware ¶
func WithCustomMiddleware(mw ...ai.Middleware) core.GenerateOption
WithCustomMiddleware adds arbitrary genkit middleware to the generation.
func WithFallback ¶
func WithFallback(modelRefs []ai.ModelRef) core.GenerateOption
WithFallback enables model fallback when the primary model fails.
func WithFilesystem ¶
func WithFilesystem(rootDir string, allowWrite bool) core.GenerateOption
WithFilesystem enables scoped file system access for the model.
func WithMiddleware ¶
func WithMiddleware(cfg *MiddlewareConfig) core.GenerateOption
WithMiddleware is a GenerateOption that injects genkit middleware into generation.
func WithRetry ¶
func WithRetry(maxRetries int) core.GenerateOption
WithRetry enables automatic retry with the specified configuration.
func WithRetryAndBackoff ¶
func WithRetryAndBackoff(maxRetries, initialDelayMs, maxDelayMs int) core.GenerateOption
WithRetryAndBackoff enables retry with custom backoff parameters.
func WithToolApproval ¶
func WithToolApproval(allowedTools []string) core.GenerateOption
WithToolApproval requires explicit approval for all tool calls.
Types ¶
type DatalogValidator ¶
type DatalogValidator struct {
// Validator is called before and after generation to enforce Datalog rules.
Validator func(ctx context.Context, phase string, req *ai.ModelRequest, resp *ai.ModelResponse) error
}
DatalogValidator is a custom middleware that validates generation input/output using Datalog rules before and after model calls.
func (*DatalogValidator) Name ¶
func (d *DatalogValidator) Name() string
type Example ¶
type Example struct{}
Example: Complete generation with all middleware
func (*Example) GenerateWithFullMiddleware ¶
func (e *Example) GenerateWithFullMiddleware( ctx context.Context, gen core.TextGenerator, prompt string, ) (*core.LLMResponse, error)
GenerateWithFullMiddleware demonstrates using all middleware features.
type GenerationOption ¶
type GenerationOption func(*GenerationSettings)
GenerationOption is a functional option for configuring generation with middleware.
func WithDatalogValidator ¶
func WithDatalogValidator(validator func(ctx context.Context, phase string, req *ai.ModelRequest, resp *ai.ModelResponse) error) GenerationOption
WithDatalogValidator adds Datalog validation middleware.
func WithFallbackMiddleware ¶
func WithFallbackMiddleware(models ...ai.ModelRef) GenerationOption
WithFallbackMiddleware enables fallback to alternative models.
func WithFilesystemMiddleware ¶
func WithFilesystemMiddleware(rootDir string, allowWrite bool) GenerationOption
WithFilesystemMiddleware enables scoped filesystem access.
func WithGenerationConfig ¶
func WithGenerationConfig(cfg *core.GenerationConfig) GenerationOption
WithGenerationConfig sets the base generation config.
func WithLogging ¶
func WithLogging(logger core.Logger) GenerationOption
WithLogging adds logging middleware.
func WithRetryMiddleware ¶
func WithRetryMiddleware(maxRetries int) GenerationOption
WithRetryMiddleware enables retry middleware with default settings.
func WithTelemetry ¶
func WithTelemetry(onGenerate func(ctx context.Context, duration time.Duration, model string, inputTokens, outputTokens int)) GenerationOption
WithTelemetry adds telemetry collection middleware.
func WithToolApprovalMiddleware ¶
func WithToolApprovalMiddleware(allowedTools ...string) GenerationOption
WithToolApprovalMiddleware requires approval for tool execution.
type GenerationSettings ¶
type GenerationSettings struct {
Config *core.GenerationConfig
Middleware *MiddlewareConfig
}
GenerationSettings holds all generation configuration including middleware.
type GenkitTextGenerator ¶
type GenkitTextGenerator interface {
core.TextGenerator
GenkitModel() ai.Model
GenkitInstance() *genkit.Genkit
}
GenkitTextGenerator is the exported interface for adapters backed by a Genkit model. It extends core.TextGenerator with access to the underlying Genkit model and runtime for native features (structured output, middleware).
type LLMAction ¶
type LLMAction struct {
// contains filtered or unexported fields
}
LLMAction is a concrete implementation of core.Action that wraps a core.TextGenerator. It adapts the specific TextGenerator interface to the universal core.Action envelope interface.
func NewLLMAction ¶
func NewLLMAction(name string, generator core.TextGenerator) (*LLMAction, error)
NewLLMAction creates a new LLMAction instance.
Parameters:
- name: A unique name for this action (used in observability and policies).
- generator: The TextGenerator implementation to wrap.
Returns:
- A pointer to the initialized LLMAction.
- An error if the generator is nil.
func (*LLMAction) Execute ¶
Execute performs the text generation. It expects the input Envelope's Payload to be a string (the prompt). It returns a new Envelope containing the generated text as the Payload.
Parameters:
- ctx: The execution context.
- input: The input envelope containing the prompt string.
Returns:
- A result envelope with the generated text, or an error.
func (*LLMAction) Generate ¶
func (a *LLMAction) Generate(ctx context.Context, prompt string, opts ...core.GenerateOption) (*core.LLMResponse, error)
Generate implements core.TextGenerator.
func (*LLMAction) Metadata ¶
func (a *LLMAction) Metadata() core.ActionMetadata
Metadata returns the static metadata for this action.
type LoggingMiddleware ¶
LoggingMiddleware is a custom middleware that logs generation details.
func (*LoggingMiddleware) Name ¶
func (l *LoggingMiddleware) Name() string
type MiddlewareConfig ¶
type MiddlewareConfig struct {
// Retry configures automatic retry with exponential backoff.
Retry *middleware.Retry
// Fallback configures alternative model fallback on failure.
Fallback *middleware.Fallback
// ToolApproval requires explicit approval for tool execution.
ToolApproval *middleware.ToolApproval
// Filesystem enables scoped file system access for the model.
Filesystem *middleware.Filesystem
// CustomMiddlewares allows injecting arbitrary middleware.
CustomMiddlewares []ai.Middleware
}
MiddlewareConfig holds genkit middleware settings for a generation call. Use this with GenerateOption to configure per-call middleware.
func ComposeMiddleware ¶
func ComposeMiddleware(opts ...GenerationOption) (*MiddlewareConfig, error)
ComposeMiddleware creates a single MiddlewareConfig from multiple options. This is useful when you want to build middleware incrementally.
type StreamingGate ¶ added in v0.7.0
type StreamingGate interface {
Assess(ctx context.Context, actionMeta core.ActionMetadata, input core.Envelope) error
Reflect(ctx context.Context, actionMeta core.ActionMetadata, output core.Envelope) (core.Envelope, error)
}
StreamingGate is the governance surface a StreamingSupervisedAction needs: the pre-check (Assess) that runs before the first chunk is produced, and the post-check (Reflect) that runs on the assembled full response once the stream completes. core.Evaluator (sdk.Client.Engine) satisfies it.
type StreamingSupervisedAction ¶ added in v0.7.0
type StreamingSupervisedAction struct {
// contains filtered or unexported fields
}
StreamingSupervisedAction wraps a core.TextGenerator so that streaming generation is supervised by the governance gate:
- Pre-check (Assess) runs before the provider stream is opened, so a policy deny halts the action before a single chunk is generated.
- Chunks are forwarded to the caller as they arrive.
- Post-check (Reflect) runs on the assembled full response after the stream completes. If it denies, the caller receives a terminal core.StreamChunk carrying the policy error and no final envelope is exposed.
func NewStreamingSupervisedAction ¶ added in v0.7.0
func NewStreamingSupervisedAction(name string, generator core.TextGenerator, gate StreamingGate) (*StreamingSupervisedAction, error)
NewStreamingSupervisedAction creates a streaming supervised LLM action.
Parameters:
- name: A unique action name (used in policies and observability).
- generator: The TextGenerator providing the underlying stream.
- gate: The governance gate (pre/post-check); typically client.Engine().
func (*StreamingSupervisedAction) Execute ¶ added in v0.7.0
func (a *StreamingSupervisedAction) Execute(ctx context.Context, input core.Envelope) (core.Envelope, error)
Execute performs a non-streaming supervised generation: pre-check, Complete, post-check on the full response.
func (*StreamingSupervisedAction) FinalEnvelope ¶ added in v0.7.0
func (a *StreamingSupervisedAction) FinalEnvelope() (core.Envelope, bool)
FinalEnvelope returns the post-checked assembled response, if the stream has completed and the post-check passed.
func (*StreamingSupervisedAction) Metadata ¶ added in v0.7.0
func (a *StreamingSupervisedAction) Metadata() core.ActionMetadata
Metadata returns the static metadata for this action.
func (*StreamingSupervisedAction) Stream ¶ added in v0.7.0
func (a *StreamingSupervisedAction) Stream(ctx context.Context, input core.Envelope) (<-chan core.StreamChunk, error)
Stream performs a supervised streaming generation. The pre-check runs synchronously before the provider stream is opened: when the policy denies the request, Stream returns the policy error and no channel is created, so the caller never receives a chunk. On success, chunks are forwarded as they arrive; after the underlying stream closes the assembled full response is post-checked (Reflect). A post-check denial surfaces as a terminal core.StreamChunk with the policy error (available via FinalEnvelope only when the post-check passes).
type TelemetryMiddleware ¶
type TelemetryMiddleware struct {
OnGenerate func(ctx context.Context, duration time.Duration, model string, inputTokens, outputTokens int)
}
TelemetryMiddleware is a custom middleware that records generation metrics.
func (*TelemetryMiddleware) Name ¶
func (t *TelemetryMiddleware) Name() string