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)
- type AgentConfig
- func BuildFromConfig(config AgentConfig, baseDir string, catalog *GlobalCatalog, ...) (*agent.AgentLoop, *history.InMemSessionManager, 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 BuildFromYAMLBytesWithSession(data []byte, baseDir string, catalog *GlobalCatalog, llm agent.LLMProvider, ...) (*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 ParseYAMLConfig(yamlPath string) (AgentConfig, error)
- type GlobalCatalog
- type KBDocument
- type KBFilter
- 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.
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"`
} `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
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 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 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 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 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.
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.
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 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