sdk

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 11, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Overview

Package sdk provides the Manglekit SDK. This file contains the Policy Copilot logic (formerly rulegenerator).

Index

Constants

View Source
const (
	// TracerName is the instrumentation scope name for Manglekit tracing.
	TracerName = "github.com/duynguyendang/manglekit/sdk"

	// Failure modes determine the system's resilience strategy.
	FailModeOpen   = "open"   // Allow execution on system error (Fail-Open)
	FailModeClosed = "closed" // Block execution on system error (Fail-Closed)
)
View Source
const (
	DefaultMaxSteps   = 10
	DefaultMaxRetries = 3
	BackoffBase       = 100 * time.Millisecond
)

Define constants or config struct

View Source
const DefaultExamples = `` /* 386-byte string literal not displayed */

DefaultExamples provides standard few-shot examples for the LLM. These examples cover common patterns like numerical comparison and string matching.

View Source
const DefaultPromptTemplate = `` /* 791-byte string literal not displayed */

DefaultPromptTemplate is the default system prompt used to instruct the LLM. It sets constraints on syntax, predicate usage, and output format.

Variables

This section is empty.

Functions

func Execute

func Execute[TIn any, TOut any](
	ctx context.Context,
	c *Client,
	handle TypedAction[TIn, TOut],
	input TIn,
) (TOut, error)

Execute runs a typed action against the client. It guarantees that the input matches TIn and attempts to convert the output to TOut.

func HydrateActions

func HydrateActions(ctx context.Context, actions map[string]config.ActionConfig) ([]core.Action, error)

HydrateActions iterates through the configuration and instantiates the defined actions. It acts as a high-level factory for converting config maps into executable core.Actions.

func NewActionFromConfig

func NewActionFromConfig(ctx context.Context, name string, cfg config.ActionConfig) (core.Action, error)

NewActionFromConfig creates a new Action instance based on the provided configuration.

func RegisterMemoryProvider

func RegisterMemoryProvider(name string, factory MemoryFactory)

RegisterMemoryProvider allows plugins to register memory backends (e.g., "qdrant", "simple").

func RegisterProvider

func RegisterProvider(name string, factory ProviderFactory)

RegisterProvider allows external packages (plugins) to register their factories. Example: sdk.RegisterProvider("google", GoogleFactory)

func WithExtractor

func WithExtractor(action core.Action, ext ports.Extractor) core.Action

WithExtractor sets the text-to-struct extractor on a supervised action. This enables the neuro-symbolic bridge: free-text LLM responses are extracted to structured data before flattenToQuads, so Datalog rules can fire on the result.

The extractor is only invoked when the action payload is a string (free text). Struct/JSON payloads bypass the extractor (fast path preserved).

Parameters:

  • action: A supervised action (from Client.Supervise()).
  • ext: The extractor to use (implements ports.Extractor).

Returns:

  • The action with extractor set.

func WithJSONMode

func WithJSONMode(enabled bool) core.GenerateOption

WithJSONMode enables JSON mode.

func WithMaxTokens

func WithMaxTokens(n int) core.GenerateOption

WithMaxTokens sets the maximum number of tokens to generate.

func WithModel

func WithModel(m string) core.GenerateOption

WithModel sets the model to use.

func WithStopSequences

func WithStopSequences(seqs []string) core.GenerateOption

WithStopSequences sets the stop sequences.

func WithStructuredOutput

func WithStructuredOutput(schema any) core.GenerateOption

WithStructuredOutput sets the output type for structured generation.

func WithTemperature

func WithTemperature(t float64) core.GenerateOption

WithTemperature sets the sampling temperature.

func WithTopP

func WithTopP(p float64) core.GenerateOption

WithTopP sets the nucleus sampling probability.

Types

type ActionMetadata

type ActionMetadata = core.ActionMetadata

ActionMetadata provides metadata about an action.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the primary entry point for the Manglekit system. It acts as the governance kernel, managing blueprints, observability, and action execution. Applications should create a single Client instance and reuse it.

func Must

func Must(c *Client, err error) *Client

Must ensures that the client initialization succeeded. If err is not nil, it panics. This is useful for concise initialization in main() functions.

Parameters:

  • c: The client instance.
  • err: The error returned by the constructor.

Returns:

  • The valid Client instance.

func NewClient

func NewClient(ctx context.Context, opts ...ClientOption) (*Client, error)

NewClient initializes a new Manglekit Client with the provided options. It sets up the Policy Engine, Observability (Logging/Tracing), and default configurations.

Parameters:

  • ctx: The initialization context.
  • opts: A variadic list of ClientOption configuration functions.

Returns:

  • A pointer to the initialized Client, or an error if initialization fails.

func NewClientFromConfig

func NewClientFromConfig(ctx context.Context, cfg *config.Config, opts ...ClientOption) (*Client, error)

NewClientFromConfig initializes a Client using a pre-loaded Config object.

func NewClientFromFile

func NewClientFromFile(ctx context.Context, configPath string, opts ...ClientOption) (*Client, error)

NewClientFromFile initializes a Client by loading configuration from a YAML file.

func NewDefault

func NewDefault() (*Client, error)

NewDefault initializes a Client with sensible default settings.

func TryClient

func TryClient(c *Client, err error) (*Client, error)

TryClient attempts client initialization and returns a non-panicking error. Prefer this over Must() in library code or tests where panics are inappropriate.

Returns:

  • The valid Client instance, or a zero-value Client and the initialization error.

func (*Client) Action

func (c *Client) Action(name string) core.Action

Action returns a handle to a registered action that implements the core.Action interface. This allows registered actions (like LLMs) to be injected into other components that expect a core.Action dependency.

func (*Client) Engine

func (c *Client) Engine() core.Evaluator

Engine returns the underlying policy engine (Evaluator).

func (*Client) Execute

func (c *Client) Execute(ctx context.Context, input core.Envelope, opts ...ExecuteOption) (core.Envelope, error)

Execute processes an envelope by determining the initial action via the policy engine. It relies on the 'next_step' predicate to route the request. When steering is disabled (steeringEnabled=false), this returns an error because no Datalog-driven routing is available.

func (*Client) ExecuteByName

func (c *Client) ExecuteByName(ctx context.Context, actionName string, input any, opts ...ExecuteOption) (core.Envelope, error)

ExecuteByName executes a registered action by its name, handling the Semantic State Machine loop.

func (*Client) ExecutePlan

func (c *Client) ExecutePlan(ctx context.Context, steps []PlanStep, initialInput core.Envelope) (core.Envelope, error)

ExecutePlan executes a generated plan sequentially. It chains the output of one step as the input to the next.

Parameters:

  • ctx: The execution context.
  • steps: The ordered list of steps to execute.
  • initialInput: The input envelope for the first step.

Returns:

  • The final output envelope.
  • An error if any step fails.

func (*Client) ExecuteSingleStep

func (c *Client) ExecuteSingleStep(ctx context.Context, actionName string, payload any, params *ExecutionParams) (core.Envelope, error)

ExecuteSingleStep runs one step of the action and returns the decision. It orchestrates: Context Injection → Execution → History → Decision Handling.

func (*Client) LoadFacts

func (c *Client) LoadFacts(facts []string) error

LoadFacts allows manually injecting straight Datalog facts into the engine.

func (*Client) LoadGherkinPolicy

func (c *Client) LoadGherkinPolicy(ctx context.Context, featureContent string) error

LoadGherkinPolicy loads a Gherkin feature file and compiles it to Datalog.

func (*Client) LoadNTriplesFile

func (c *Client) LoadNTriplesFile(path string) error

LoadNTriplesFile opens a .nt file, parses it, and loads facts into the engine.

func (*Client) Logger

func (c *Client) Logger() core.Logger

Logger returns the configured Logger instance.

func (*Client) Memory

func (c *Client) Memory() core.AgentMemory

Memory returns the active memory provider (if any).

func (*Client) Plan

func (c *Client) Plan(ctx context.Context, goalName string) ([]PlanStep, error)

Plan generates a sequence of actions (a plan) to achieve the specified goal. It uses the underlying Datalog engine to reason about goals and subgoals.

Parameters:

  • ctx: The context.
  • goalName: The name of the goal to achieve (e.g., "onboard_user").

Returns:

  • A slice of PlanStep structs ordered by execution sequence.
  • An error if planning fails.

func (*Client) RegisterAction

func (c *Client) RegisterAction(name string, action core.Action)

RegisterAction adds an action to the client's internal registry.

func (*Client) SetLLM

func (c *Client) SetLLM(gen core.TextGenerator)

SetLLM manually configures the TextGenerator (LLM) for the client. This is useful for code-first wiring or when using provider factories.

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

Shutdown cleans up resources used by the client. Safe to call multiple times; subsequent calls return nil.

func (*Client) Supervise

func (c *Client) Supervise(action core.Action) core.Action

Supervise wraps a raw core.Action in a SupervisedAction using v2 patterns.

func (*Client) Tracer

func (c *Client) Tracer() trace.Tracer

Tracer returns the OpenTelemetry Tracer used by the client.

type ClientOption

type ClientOption func(*Client) error

ClientOption configures the Manglekit Client during initialization.

func WithAgentMemory

func WithAgentMemory(mem core.AgentMemory) ClientOption

WithAgentMemory configures the semantic memory (RAG) provider.

Parameters:

  • mem: A core.AgentMemory implementation.

func WithBlueprintPath

func WithBlueprintPath(path string) ClientOption

WithBlueprintPath specifies the file path to load Datalog rules from. "Blueprint" is the new terminology for "Policy".

The actual file I/O is deferred until the Client is fully constructed, using the context passed to NewClient. This avoids context.Background() and enables proper cancellation propagation.

Parameters:

  • path: A file path to the .dl blueprint file.

func WithConfig

func WithConfig(cfg *config.Config) ClientOption

WithConfig applies settings from a loaded configuration struct. It handles wiring of providers, actions, policy, knowledge, and memory.

func WithEngine

func WithEngine(e core.Evaluator) ClientOption

WithEngine allows injecting a custom or mock core.Evaluator.

func WithFailMode

func WithFailMode(mode string) ClientOption

WithFailMode sets the resilience strategy for the client.

Parameters:

  • mode: "open" (allow execution on error) or "closed" (block execution on error).

func WithHistory

func WithHistory(store core.HistoryStore) ClientOption

WithHistory configures a custom persistence store for chat history.

Parameters:

  • store: A core.HistoryStore implementation (e.g., Redis backed).

func WithLLM

func WithLLM(gen core.TextGenerator) ClientOption

WithLLM configures the AI backend for the client. This supports the "Explicit AI Adapter" pattern where the application initializes the model (e.g., via Genkit) and passes it to the SDK.

Parameters:

  • gen: A core.TextGenerator implementation (e.g., adapters.ai.NewGenkitAdapter(model)).

func WithLogger

func WithLogger(l core.Logger) ClientOption

WithLogger sets a custom logger for the client.

Parameters:

  • l: A core.Logger implementation.

func WithMemory

func WithMemory(mem core.AgentMemory) ClientOption

WithMemory allows injecting a custom memory implementation (e.g., Hybrid HNSW).

func WithProviderConfig

func WithProviderConfig(name string, cfg config.ActionConfig) ClientOption

WithProviderConfig creates a ClientOption that initializes a provider from configuration. It looks up the factory, creates the ClientOption, and applies it.

func WithStateProvider

func WithStateProvider(provider core.StateProvider) ClientOption

WithStateProvider configures the state provider for durable session persistence. This enables automatic checkpointing and recovery of session state across restarts.

Parameters:

  • provider: A core.StateProvider implementation (e.g., disk, Redis).

func WithStdoutTracer

func WithStdoutTracer() ClientOption

WithStdoutTracer configures the client to use a standard output tracer. This is useful for development and debugging to see traces in the console.

func WithTracerProvider

func WithTracerProvider(tp trace.TracerProvider) ClientOption

WithTracerProvider configures the OpenTelemetry tracer provider. This enables Manglekit to emit spans to your existing tracing infrastructure.

Parameters:

  • tp: The OpenTelemetry TracerProvider.

type Envelope

type Envelope = core.Envelope

Envelope is the standard communication structure for actions.

func NewEnvelope

func NewEnvelope(payload any) Envelope

NewEnvelope creates a new envelope with the given payload. This is a convenience re-export of core.NewEnvelope.

type ExecuteOption

type ExecuteOption func(*ExecutionParams)

ExecuteOption configures a single execution call (e.g., ExecuteByName).

func WithMaxSteps

func WithMaxSteps(n int) ExecuteOption

WithMaxSteps sets the maximum number of loop iterations allowed. Zero uses the default (DefaultMaxSteps = 10).

func WithMetadata

func WithMetadata(key, value string) ExecuteOption

WithMetadata injects custom key-value pairs into the execution envelope's metadata. This is useful for passing context like "user_id" or "source" to the policy engine.

Parameters:

  • key: The metadata key.
  • value: The metadata value.

func WithMetadataMap

func WithMetadataMap(meta map[string]any) ExecuteOption

WithMetadataMap injects a map of custom key-value pairs into the execution envelope's metadata. Non-string values are converted using fmt.Sprintf("%v", v).

func WithSessionID

func WithSessionID(id string) ExecuteOption

WithSessionID activates persistent stateful mode for the execution. It links the execution to a specific session history.

Parameters:

  • id: The session identifier.

func WithTransientMemory

func WithTransientMemory() ExecuteOption

WithTransientMemory activates in-memory stateful mode. History is tracked for the duration of the loop/process but not persisted.

type ExecutionParams

type ExecutionParams struct {
	// SessionID is the unique identifier for a conversation/session.
	SessionID string
	// MemoryMode determines how chat history is handled (None, Transient, Persist).
	MemoryMode core.MemoryMode
	// Metadata contains additional context to be injected into the execution envelope.
	Metadata map[string]string
	// MaxSteps limits the total number of loop iterations.
	// Zero uses the default (DefaultMaxSteps).
	MaxSteps int

	// AuditRecords accumulates governance audit trail across steps.
	// Appended per step — persisted on checkpoint.
	AuditRecords []core.AuditRecord

	// State fields (Managed by ExecuteSingleStep/Loop)
	Store           core.HistoryStore `json:"-"` // Internal store reference
	CurrentHistory  []core.Message    `json:"history,omitempty"`
	FeedbackHistory []string          `json:"feedback_history,omitempty"`
	LastFeedback    string            `json:"last_feedback,omitempty"`
	RetryCount      int               `json:"retry_count,omitempty"`
}

ExecutionParams holds the configuration for a specific execution run.

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator facilitates the translation of natural language policies into Mangle Datalog rules. It leverages an underlying LLM (wrapped as a core.Action) to perform the translation.

func NewPolicyGenerator

func NewPolicyGenerator(llmAction core.Action, opts GeneratorOptions) (*Generator, error)

NewPolicyGenerator creates a new Generator instance.

Parameters:

  • llmAction: A core.Action that wraps an LLM (e.g., via adapters/ai). It must accept a string prompt and return a string response.
  • opts: Configuration options for the generator.

Returns:

  • A pointer to the Generator, or an error if initialization fails.

func (*Generator) GenerateRule

func (g *Generator) GenerateRule(ctx context.Context, schemaSample any, policyText string) (string, error)

GenerateRule translates a natural language policy into a Datalog rule using In-Context Learning. It dynamically extracts the schema from the provided sample struct to teach the LLM available predicates.

Workflow:

  1. Extract schema predicates from `schemaSample`.
  2. Construct a prompt containing the schema, examples, and user policy.
  3. Invoke the LLM action.
  4. Parse and verify the generated Datalog rule.

Parameters:

  • ctx: The context.
  • schemaSample: A Go struct instance representing the data model (used to generate available predicates).
  • policyText: The natural language policy to translate (e.g., "Block transactions over $1000").

Returns:

  • The generated Datalog rule string, or an error.

type GeneratorOptions

type GeneratorOptions struct {
	// RuleHead defines the target predicate signature (e.g., "deny(Req)", "allow(Req)", "route(Req, Target)").
	// It guides the LLM to produce a rule that matches this head.
	// Default: "deny(Req)"
	RuleHead string

	// PromptTemplate is a custom Go template string used to instruct the LLM.
	// It must contain placeholders for {{.SchemaContext}}, {{.Examples}}, and {{.UserPolicy}}.
	// If empty, the internal DefaultPromptTemplate is used.
	PromptTemplate string

	// Examples provides few-shot learning examples inserted into the prompt template.
	// This helps the LLM understand the expected Datalog syntax and logic patterns.
	// If empty, the internal DefaultExamples is used.
	Examples string
}

GeneratorOptions defines configuration for the rule generator.

type HybridMemory

type HybridMemory struct {
	History        core.HistoryStore
	Vectors        core.VectorStore
	Embedder       core.Embedder // Kept for interface compatibility, but VectorStore handles embedding.
	CollectionName string        // Deprecated: VectorStore handles collections internally or ignores them.
	TopK           int           // Number of results to retrieve (default: 3)
}

HybridMemory implements core.AgentMemory by combining: 1. HistoryStore (Sequential Chat Logs) 2. VectorStore (Semantic Search / RAG)

func NewHybridMemory

func NewHybridMemory(h core.HistoryStore, v core.VectorStore, e core.Embedder) *HybridMemory

NewHybridMemory creates a new memory orchestrator with default RAG settings.

func (*HybridMemory) Append

func (m *HybridMemory) Append(ctx context.Context, sessionID string, msgs []core.Message) error

Append adds new messages to the history.

func (*HybridMemory) Init

func (m *HybridMemory) Init(ctx context.Context) error

Init performs any necessary setup.

func (*HybridMemory) Memorize

func (m *HybridMemory) Memorize(ctx context.Context, query string, answer string) error

Memorize stores a new interaction (Input/Output) for future recall.

func (*HybridMemory) Read

func (m *HybridMemory) Read(ctx context.Context, sessionID string) ([]core.Message, error)

Read retrieves the chat history for a given session.

func (*HybridMemory) Recall

func (m *HybridMemory) Recall(ctx context.Context, query string) (string, error)

Recall retrieves relevant context based on the current query.

type MemoryFactory

type MemoryFactory func(ctx context.Context, cfg config.MemoryConfig) (core.AgentMemory, error)

MemoryFactory defines the constructor for memory providers.

func MemoryProvider

func MemoryProvider(name string) (MemoryFactory, error)

MemoryProvider retrieves a registered memory factory.

type PlanStep

type PlanStep struct {
	ActionName string
	Order      int
}

PlanStep represents a single step in a generated plan.

type ProviderFactory

type ProviderFactory func(opts map[string]any) (ClientOption, error)

ProviderFactory defines the constructor signature for creating an action from config. Strict Mode: Returns a ClientOption to configure the client directly.

func Provider

func Provider(name string) (ProviderFactory, error)

Provider retrieves a registered factory.

type Runnable

type Runnable[In any, Out any] struct {
	// contains filtered or unexported fields
}

Runnable is a handle for a type-safe action

func Define

func Define[In any, Out any](
	c *Client,
	name string,
	handler func(context.Context, In) (Out, error),
) *Runnable[In, Out]

Define registers a pure Go function as an Action

func (*Runnable[In, Out]) Run

func (r *Runnable[In, Out]) Run(ctx context.Context, input In) (Out, error)

Run executes the action with strict types

type TypedAction

type TypedAction[TIn any, TOut any] struct {
	Name string
}

TypedAction serves as a strongly-typed handle for a registered action. It creates a contract between the caller and the engine without code generation.

TIn: The Go struct type required for Input. TOut: The Go struct type guaranteed for Output.

func DefineAction

func DefineAction[TIn any, TOut any](name string) TypedAction[TIn, TOut]

DefineAction creates a new typed handle. This should be used in a shared "definitions" package or at the top of main.

Example:

var ActionTransfer = sdk.DefineAction[TransferReq, TransferResp]("transfer_money")

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL