Documentation
¶
Overview ¶
Package builder provides YAML-driven agent configuration and a global tool catalog.
Index ¶
- func DynamicKB(fn func(ctx context.Context, sessionKey string) []KBDocument) agent.DynamicContextFunc
- func FormatKnowledgeBase(docs []KBDocument) string
- func LoadKnowledgeBase(dir string) (string, error)
- func LoadKnowledgeBaseFiltered(dir string, filter KBFilter) (string, error)
- func WithKnowledgeBase(basePrompt, dir string) (string, error)
- func WithKnowledgeBaseDocs(basePrompt string, docs []KBDocument) string
- func WithKnowledgeBaseFiltered(basePrompt, dir string, filter KBFilter) (string, error)
- func WithSkillCatalog(basePrompt string, set *skills.Set) string
- type AgentConfig
- func BuildFromConfig(config AgentConfig, baseDir string, catalog *GlobalCatalog, ...) (*agent.AgentLoop, *history.InMemSessionManager, AgentConfig, error)
- func BuildFromConfigContext(ctx context.Context, config AgentConfig, baseDir string, ...) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
- func BuildFromConfigWithSession(config AgentConfig, baseDir string, catalog *GlobalCatalog, ...) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
- func BuildFromYAML(yamlPath string, catalog *GlobalCatalog, llm agent.LLMProvider, ...) (*agent.AgentLoop, *history.InMemSessionManager, AgentConfig, error)
- func BuildFromYAMLBytes(data []byte, baseDir string, catalog *GlobalCatalog, llm agent.LLMProvider, ...) (*agent.AgentLoop, *history.InMemSessionManager, AgentConfig, error)
- func BuildFromYAMLBytesContext(ctx context.Context, data []byte, baseDir string, catalog *GlobalCatalog, ...) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
- func BuildFromYAMLBytesWithSession(data []byte, baseDir string, catalog *GlobalCatalog, llm agent.LLMProvider, ...) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
- func BuildFromYAMLContext(ctx context.Context, yamlPath string, catalog *GlobalCatalog, ...) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
- func BuildFromYAMLWithSession(yamlPath string, catalog *GlobalCatalog, llm agent.LLMProvider, ...) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
- func ParseYAMLBytes(data []byte, baseDir string) (AgentConfig, error)
- func ParseYAMLBytesContext(ctx context.Context, data []byte, baseDir string) (AgentConfig, error)
- func ParseYAMLConfig(yamlPath string) (AgentConfig, error)
- func ParseYAMLConfigContext(ctx context.Context, yamlPath string) (AgentConfig, error)
- type GlobalCatalog
- type KBDocument
- type KBFilter
- type SkillSource
- type SkillsConfig
- type YAMLValidationError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DynamicKB ¶
func DynamicKB(fn func(ctx context.Context, sessionKey string) []KBDocument) agent.DynamicContextFunc
DynamicKB lifts a KB-document producer into an agent.DynamicContextFunc by rendering the documents through FormatKnowledgeBase. The output is the same <knowledge_base><file path="…">…</file></knowledge_base> block that the builder uses at build time, so static KB loaded from YAML and dynamic KB from this adapter are indistinguishable to the LLM.
The block is delivered as a tail message (not folded into the system prompt) so the historical prefix stays byte-identical across dynamic changes — static KB from YAML still benefits from Anthropic prompt caching regardless of how often the dynamic KB rotates.
Returning an empty slice (or nil) yields an empty string, which causes agent.withDynamicContext to skip augmentation for that call.
All contracts documented on agent.DynamicContextFunc — hot-path budget, turn-level stability, and prompt-cache placement — apply unchanged.
func FormatKnowledgeBase ¶
func FormatKnowledgeBase(docs []KBDocument) string
FormatKnowledgeBase returns docs wrapped in the standard <knowledge_base>…</knowledge_base> block with one <file path="…">…</file> entry per document, sorted by Path so the output is stable across runs — important when downstream consumers hash the system prompt for prompt-cache breakpoints. Returns "" when no document carries usable content.
func LoadKnowledgeBase ¶
LoadKnowledgeBase walks dir recursively, reads every text file whose extension is in kbExtensions, and returns the FormatKnowledgeBase output for the resulting document set. Relative paths inside the block use forward slashes regardless of host OS. It is LoadKnowledgeBaseFiltered with an empty (match-all) filter.
An empty dir, or a dir with no whitelisted files, yields ("", nil) so callers can unconditionally append the result to a system prompt.
The function deliberately has no size cap; pointing it at a 1GB directory will produce a 1GB prompt and break the LLM request. Trust the caller to point it at curated reference material.
func LoadKnowledgeBaseFiltered ¶
LoadKnowledgeBaseFiltered is LoadKnowledgeBase restricted to the OKF concepts matching filter. It parses YAML frontmatter from each file, strips it from the injected body, and keeps only documents the filter admits. A zero filter loads everything.
func WithKnowledgeBase ¶
WithKnowledgeBase returns basePrompt with the KB block loaded from dir appended after a blank line. The block is appended (not prepended) so task-specific instructions in basePrompt stay closest to the user message — LLMs weight late-prompt tokens more heavily.
When dir is empty or contains no whitelisted files, basePrompt is returned unchanged.
func WithKnowledgeBaseDocs ¶
func WithKnowledgeBaseDocs(basePrompt string, docs []KBDocument) string
WithKnowledgeBaseDocs is the in-memory analog of WithKnowledgeBase: useful when KB content comes from a database, an HTTP upload, or any runtime source rather than a directory on disk.
When docs is empty or every entry is blank, basePrompt is returned unchanged.
func WithKnowledgeBaseFiltered ¶
WithKnowledgeBaseFiltered is WithKnowledgeBase with an OKF metadata filter applied before injection — load only the concept types/tags this agent needs instead of the whole tree, keeping the system prompt within budget. A zero filter behaves exactly like WithKnowledgeBase.
func WithSkillCatalog ¶ added in v0.36.0
WithSkillCatalog returns basePrompt with the skill catalog appended after a blank line, mirroring WithKnowledgeBase.
The catalog belongs in the system prompt rather than in a per-request injection: it is fixed for the process lifetime, so it sits inside the stable prefix an Anthropic cache breakpoint covers. It is also why this does not go through agent.DynamicContext — that is a single slot, and claiming it here would silently displace whatever the adopter put there.
Returns basePrompt unchanged when set is nil or empty.
Types ¶
type AgentConfig ¶
type AgentConfig struct {
Agent struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Model string `yaml:"model"`
MaxIterations int `yaml:"max_iterations"`
EmitThoughts *bool `yaml:"emit_thoughts,omitempty"`
SystemPrompt string `yaml:"system_prompt"`
ToolsRequired []string `yaml:"tools_required"`
// KnowledgeBase, when non-empty, is a directory path (relative to
// the YAML file's directory, or absolute) whose whitelisted text
// files are concatenated and appended to SystemPrompt at build
// time. See LoadKnowledgeBase for the file selection rules.
KnowledgeBase string `yaml:"knowledge_base,omitempty"`
// Skills, when set, loads skill directories whose catalog is
// appended to SystemPrompt and whose activation tools are
// registered alongside ToolsRequired. See SkillsConfig.
Skills *SkillsConfig `yaml:"skills,omitempty"`
} `yaml:"agent"`
}
AgentConfig represents the exact schema users map their YAML files to.
agent:
name: "My Agent" # required
description: "What this agent does" # optional
model: "gpt-4o" # optional (informational)
max_iterations: 15 # optional (default: 15)
emit_thoughts: true # optional (default: true)
system_prompt: | # required
You are a helpful assistant.
tools_required: # optional
- "web_search"
- "read_url"
knowledge_base: "./kb" # optional — directory of reference
# docs auto-appended to system_prompt
skills: # optional — progressive disclosure
sources: # catalog in the prompt, bodies on demand
- "./skills"
func BuildFromConfig ¶
func BuildFromConfig(config AgentConfig, baseDir string, catalog *GlobalCatalog, llm agent.LLMProvider, hook agent.Hook) (*agent.AgentLoop, *history.InMemSessionManager, AgentConfig, error)
BuildFromConfig builds an agent from an already-parsed AgentConfig. Use this when the config is produced programmatically (envvars, a UI, or a non-YAML config format) and the YAML loader is not involved.
baseDir behaves the same as in BuildFromYAMLBytes.
func BuildFromConfigContext ¶ added in v0.36.0
func BuildFromConfigContext(ctx context.Context, config AgentConfig, baseDir string, catalog *GlobalCatalog, llm agent.LLMProvider, hook agent.Hook, sm agent.SessionManager) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
BuildFromConfigContext is BuildFromConfig with a context. See BuildFromYAMLContext for when the context matters.
func BuildFromConfigWithSession ¶
func BuildFromConfigWithSession(config AgentConfig, baseDir string, catalog *GlobalCatalog, llm agent.LLMProvider, hook agent.Hook, sm agent.SessionManager) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
BuildFromConfigWithSession is the session-aware variant of BuildFromConfig.
func BuildFromYAML ¶
func BuildFromYAML(yamlPath string, catalog *GlobalCatalog, llm agent.LLMProvider, hook agent.Hook) (*agent.AgentLoop, *history.InMemSessionManager, AgentConfig, error)
BuildFromYAML reads a YAML config file, validates it, resolves tools from the catalog, and returns a fully wired AgentLoop ready to run.
Returns clear, actionable error messages when the YAML has issues — designed so non-engineers (PMs, ops) can fix problems without reading Go code.
llm: the LLM provider to use. If nil, falls back to MockProvider (useful for tests). hook: optional before-hook middleware. Pass nil if not needed.
Session manager defaults to InMemSessionManager. For persistent sessions (survives restarts), use BuildFromYAMLWithSession and pass a MySQLSessionManager or FileSessionManager.
func BuildFromYAMLBytes ¶
func BuildFromYAMLBytes(data []byte, baseDir string, catalog *GlobalCatalog, llm agent.LLMProvider, hook agent.Hook) (*agent.AgentLoop, *history.InMemSessionManager, AgentConfig, error)
BuildFromYAMLBytes is like BuildFromYAML but reads the YAML document from an in-memory byte slice. Use this with Go's //go:embed to ship a single binary without an on-disk YAML file:
//go:embed agent.yaml var agentYAML []byte loop, _, cfg, err := builder.BuildFromYAMLBytes(agentYAML, "", catalog, provider, nil)
baseDir, when non-empty, is used to resolve a relative knowledge_base path. Pass "" when the YAML has no knowledge_base or when knowledge_base is absolute.
func BuildFromYAMLBytesContext ¶ added in v0.36.0
func BuildFromYAMLBytesContext(ctx context.Context, data []byte, baseDir string, catalog *GlobalCatalog, llm agent.LLMProvider, hook agent.Hook, sm agent.SessionManager) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
BuildFromYAMLBytesContext is BuildFromYAMLBytes with a context. See BuildFromYAMLContext for when the context matters.
func BuildFromYAMLBytesWithSession ¶
func BuildFromYAMLBytesWithSession(data []byte, baseDir string, catalog *GlobalCatalog, llm agent.LLMProvider, hook agent.Hook, sm agent.SessionManager) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
BuildFromYAMLBytesWithSession is the session-aware variant of BuildFromYAMLBytes.
func BuildFromYAMLContext ¶ added in v0.36.0
func BuildFromYAMLContext(ctx context.Context, yamlPath string, catalog *GlobalCatalog, llm agent.LLMProvider, hook agent.Hook, sm agent.SessionManager) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
BuildFromYAMLContext is BuildFromYAML with a context.
Use it when the config declares agent.skills: loading reads the filesystem, and this is the only variant that can cancel that work or carry a deadline into it. sm may be nil to get the default InMemSessionManager.
The other Build functions remain available unchanged and pass context.Background().
func BuildFromYAMLWithSession ¶
func BuildFromYAMLWithSession(yamlPath string, catalog *GlobalCatalog, llm agent.LLMProvider, hook agent.Hook, sm agent.SessionManager) (*agent.AgentLoop, agent.SessionManager, AgentConfig, error)
BuildFromYAMLWithSession is like BuildFromYAML but accepts any SessionManager — use this for production deployments where sessions must survive server restarts:
// MySQL-backed (persistent):
sm, _ := history.NewMySQLSessionManager(db, config.Agent.SystemPrompt)
loop, _, cfg, err := builder.BuildFromYAMLWithSession("agent.yaml", catalog, provider, nil, sm)
// File-backed (persistent, no DB required):
sm, _ := history.NewFileSessionManager("./sessions", config.Agent.SystemPrompt)
loop, _, cfg, err := builder.BuildFromYAMLWithSession("agent.yaml", catalog, provider, nil, sm)
Pass nil to fall back to the default InMemSessionManager.
func ParseYAMLBytes ¶
func ParseYAMLBytes(data []byte, baseDir string) (AgentConfig, error)
ParseYAMLBytes is the bytes counterpart to ParseYAMLConfig. Use it when the YAML document comes from //go:embed or any other in-memory source.
baseDir, when non-empty, is used to resolve a relative knowledge_base path. Pass "" when the YAML has no knowledge_base or when knowledge_base is absolute.
func ParseYAMLBytesContext ¶ added in v0.36.0
ParseYAMLBytesContext is ParseYAMLBytes with a context.
This is the //go:embed route, so it is the one a config with agent.skills is most likely to take: pass the directory the skill paths resolve against as baseDir.
func ParseYAMLConfig ¶
func ParseYAMLConfig(yamlPath string) (AgentConfig, error)
ParseYAMLConfig reads and validates a YAML config file without building the agent. Useful when you need the system prompt before constructing the session manager.
When the config declares knowledge_base, ParseYAMLConfig resolves the dir relative to yamlPath and returns SystemPrompt with the KB block already appended — downstream session managers receive the same final prompt whether callers take this shortcut or go through buildFromYAML.
func ParseYAMLConfigContext ¶ added in v0.36.0
func ParseYAMLConfigContext(ctx context.Context, yamlPath string) (AgentConfig, error)
ParseYAMLConfigContext is ParseYAMLConfig with a context, for configs that declare agent.skills.
type GlobalCatalog ¶
type GlobalCatalog struct {
// contains filtered or unexported fields
}
GlobalCatalog acts as the unified "Marketplace" where developers register their custom Tools. It is safe for concurrent use.
func NewGlobalCatalog ¶
func NewGlobalCatalog() *GlobalCatalog
NewGlobalCatalog initializes a fresh Tool Marketplace.
func (*GlobalCatalog) Get ¶
func (c *GlobalCatalog) Get(name string) (tools.Tool, error)
Get retrieves a tool by its exact string name defined in the YAML flow file.
func (*GlobalCatalog) ListNames ¶
func (c *GlobalCatalog) ListNames() []string
ListNames returns the names of all registered tools in sorted order.
func (*GlobalCatalog) Register ¶
func (c *GlobalCatalog) Register(tool tools.Tool)
Register adds a custom tool to the global marketplace so the YAML parser can resolve it.
func (*GlobalCatalog) Use ¶ added in v0.35.0
func (c *GlobalCatalog) Use(mw ...tools.Middleware)
Use registers middleware applied to every tool the catalog hands to a built agent, in registration order (outermost first, per tools.Chain). Call before building. The common use is wrapping all tools with oteltools.Instrument so a YAML-built agent gets per-tool spans and latency metrics without editing each tool. Middleware must preserve Descriptor().Name so the registry keys stay stable.
type KBDocument ¶
KBDocument is a single piece of reference material injected into the system prompt. Path is the label shown in <file path="…"> and also controls sort order; it does not need to be a real filesystem path. Content is the raw text, rendered verbatim.
Type, Title, and Tags carry OKF (Open Knowledge Format) frontmatter when the source file declared any — LoadKnowledgeBase strips the YAML block from Content and surfaces it here so the metadata reaches the model as <file> attributes instead of polluting the prompt body. They are empty for plain (non-OKF) documents.
Documents with empty Path or Content are dropped by FormatKnowledgeBase.
type KBFilter ¶
KBFilter narrows which OKF concepts LoadKnowledgeBaseFiltered injects. A zero KBFilter matches every document — the behaviour LoadKnowledgeBase relies on. When Types is non-empty a document's frontmatter `type` must be one of them; when Tags is non-empty the document must carry at least one of the listed tags. The two conditions combine with AND, letting an agent pull only the concepts it needs instead of the whole tree.
type SkillSource ¶ added in v0.36.0
type SkillSource struct {
// Dir is a path relative to the YAML file's directory, or absolute.
Dir string `yaml:"dir"`
// Trust is "trusted" (the default) or "untrusted".
//
// The shorthand form defaults to trusted, unlike skills.FromFS, which
// defaults to untrusted. A path typed into the operator's own config
// file is operator-authored by definition; making them write trust:
// trusted on every entry would produce "I configured skills and got
// nothing" for the common case, and a bound nobody reads is a bound
// nobody keeps. Mark a source untrusted when it comes from somewhere
// you did not write.
Trust string `yaml:"trust,omitempty"`
}
SkillSource is one directory of skills. It accepts either a bare string or a mapping:
sources:
- ./skills # shorthand
- dir: ./vendor
trust: untrusted
func (*SkillSource) UnmarshalYAML ¶ added in v0.36.0
func (s *SkillSource) UnmarshalYAML(node *yaml.Node) error
UnmarshalYAML accepts both the scalar shorthand and the mapping form.
type SkillsConfig ¶ added in v0.36.0
type SkillsConfig struct {
Sources []SkillSource `yaml:"sources"`
// Bound overrides. Zero uses the pkg/skills defaults, which is what
// almost every deployment should do — see that package for the figures
// and for why the catalog bound is the one that matters.
MaxSkills int `yaml:"max_skills,omitempty"`
MaxSkillBytes int64 `yaml:"max_skill_bytes,omitempty"`
MaxCatalogBytes int `yaml:"max_catalog_bytes,omitempty"`
}
SkillsConfig is the agent.skills block.
agent:
skills:
sources:
- ./skills # shorthand: trusted
- dir: ./vendor-skills
trust: untrusted
max_catalog_bytes: 16384 # optional
type YAMLValidationError ¶
type YAMLValidationError struct {
Path string // file path for context
Issues []string // human-readable issue descriptions
}
YAMLValidationError holds all validation issues found in the YAML config. Its Error() message lists every problem so the user can fix them all in one pass.
func (*YAMLValidationError) Error ¶
func (e *YAMLValidationError) Error() string