Documentation
¶
Index ¶
- Constants
- func BuildSystemPrompt(knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, ...) string
- func BuildSystemPromptWithOptions(knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, ...) string
- func GetProgressiveRAGSystemPrompt(cfg *config.Config) string
- func GetPureAgentSystemPrompt(cfg *config.Config) string
- func HistoryAsSent(history []chat.Message, retainRetrievalHistory bool) []chat.Message
- func HistoryTokenBudget(cfg *types.AgentConfig) int
- func WikiGranularityGuidance(granularity string) string
- type AgentEngine
- func (e *AgentEngine) Execute(ctx context.Context, sessionID, messageID, query string, ...) (*types.AgentState, error)
- func (e *AgentEngine) GetSkillsManager() *skills.Manager
- func (e *AgentEngine) RenderUserTurnContent(sessionID, query string) string
- func (e *AgentEngine) SetAppConfig(cfg *appconfig.Config)
- func (e *AgentEngine) SetContextCheckpointSink(sink types.ContextCheckpointSink)
- func (e *AgentEngine) SetImageDescriber(fn ImageDescriberFunc)
- func (e *AgentEngine) SetMemoryPrompt(prompt string)
- func (e *AgentEngine) SetPinnedMentions(mcpServices []*PinnedMCPServiceInfo, skills []*PinnedSkillInfo)
- func (e *AgentEngine) SetQuestionOrigin(origin *QuestionOriginInfo)
- func (e *AgentEngine) SetSkillsManager(manager *skills.Manager)
- func (e *AgentEngine) SetSteerSink(sink types.SteerSink)
- func (e *AgentEngine) SetWorkspaceLayout(layout sandbox.WorkspaceLayout)
- type BuildSystemPromptOptions
- type ImageDescriberFunc
- type KnowledgeBaseInfo
- type PinnedMCPServiceInfo
- type PinnedSkillInfo
- type PlaceholderDefinition
- type QuestionOriginInfo
- type RecentDocInfo
- type SelectedDocumentInfo
- type SystemPromptSection
Constants ¶
const ( // DefaultAgentTemperature is the default temperature for the agent DefaultAgentTemperature = 0.7 // DefaultAgentMaxIterations is the default maximum number of iterations for the agent DefaultAgentMaxIterations = 20 // DefaultUseCustomSystemPrompt is the default whether to use custom system prompt for the agent DefaultUseCustomSystemPrompt = false )
const ( WikiGranularityGuidanceFocused = `` /* 1244-byte string literal not displayed */ WikiGranularityGuidanceStandard = `` /* 1045-byte string literal not displayed */ WikiGranularityGuidanceExhaustive = `` /* 800-byte string literal not displayed */ )
Granularity guidance blocks injected into WikiCandidateSlugPrompt. The pipeline resolves a KnowledgeBase's configured granularity to one of these strings via WikiGranularityGuidance().
The three levels form a spectrum from "only the document's main subjects" to "every named thing you see". Moving down the list monotonically increases the candidate slug count, the downstream chunk-citation cost, and the noise-to-signal ratio of the wiki index.
const WikiCandidateSlugPrompt = `` /* 4877-byte string literal not displayed */
WikiCandidateSlugPrompt (Pass 0 of the chunk-cited pipeline) asks the LLM to scan a document and output the SKELETON of all entities/concepts it contains: name, slug, aliases, a short description, and a short details tiebreaker. The heavy lifting — linking each slug to concrete supporting chunks — is done in a second pass (see WikiChunkCitationPrompt). Because this prompt no longer has to carry full facts per item, it stays cheap even for long docs.
const WikiChunkCitationPrompt = `` /* 2431-byte string literal not displayed */
WikiChunkCitationPrompt (Pass 1..N of the chunk-cited pipeline) asks the LLM to read a batch of chunks and, for each candidate entity/concept, list the chunk IDs that substantively discuss it. This keeps per-slug "facts" in their verbatim form (the chunk text) instead of asking the LLM to paraphrase. Block order matters for provider prefix caching: the static rules, output schema and the per-document-stable <candidate_slugs> are placed BEFORE the per-batch <chunks> block. Within one document only ChunksXML changes between batches, so every batch after the first shares the long [rules | candidate_slugs] prefix and avoids re-billing the static rules.
const WikiDeduplicationPrompt = `` /* 5555-byte string literal not displayed */
WikiDeduplicationPrompt asks the LLM to identify duplicate entities/concepts between newly extracted items and existing wiki pages.
const WikiIndexIntroPrompt = `` /* 607-byte string literal not displayed */
WikiIndexIntroPrompt generates the introduction for a NEW index page (first time only).
const WikiIndexIntroUpdatePrompt = `` /* 850-byte string literal not displayed */
WikiIndexIntroUpdatePrompt incrementally updates an existing index introduction.
const WikiKnowledgeExtractPrompt = `` /* 5532-byte string literal not displayed */
WikiKnowledgeExtractPrompt extracts both entities and concepts in a single LLM call. Returns a JSON object with "entities" and "concepts" arrays. This replaces the former separate WikiEntityExtractPrompt and WikiConceptExtractPrompt.
const WikiPageModifyContinuationPrompt = `Your previous message was cut off because it reached the ` +
`output length limit, so the page is incomplete.
Continue the SAME message from exactly where it stopped:
1. Do NOT repeat anything you already wrote — not the SUMMARY line, not the headings, not the ` +
`rows, not the opening of the row you were in the middle of.
2. Your reply is appended verbatim to what you already wrote. Its first characters must be exactly ` +
`the characters that follow the last character of your previous message. If you stopped in the ` +
`middle of a Markdown table row, finish that row first.
3. Keep the same structure, formatting, ordering, and language as the part you already wrote.
4. Output the continuation ONLY: no preamble, no apology, no explanation, no closing code fence.
5. If the page was in fact already complete, reply with exactly: (complete)`
WikiPageModifyContinuationPrompt resumes a page rewrite that the provider cut off at the completion budget (finish_reason=length). Long enumerations are the shape that hits the cap: a certificate ledger with a hundred-plus holder rows is emitted row by row, and the provider stops the model mid-table, so the page is persisted one third short. The partial page is replayed as an assistant turn and this prompt asks for the remainder — WITHOUT the replay the model answers the original question again from the top, which is the #3446 spiral the agent loop works around.
const WikiPageModifySystemPrompt = `` /* 3148-byte string literal not displayed */
WikiPageModifySystemPrompt contains only rules shared by every page update. Keeping page identity and source data out of this message gives providers a long byte-stable prefix to cache across a reduce batch.
const WikiPageModifyUserPrompt = `` /* 3143-byte string literal not displayed */
WikiPageModifyUserPrompt contains the per-batch and per-page data. The document- level source context deliberately comes first: all pages generated from one source then share the longest possible prefix before page metadata diverges.
const WikiSummaryPrompt = `` /* 2086-byte string literal not displayed */
WikiSummaryPrompt generates a summary page for a newly ingested document.
Filename and title are intentionally NOT passed to the LLM: documents uploaded to WeKnora often carry filenames that say nothing about the content (e.g. scanned PDFs named after the scanner model "MX5280.pdf"), and feeding such filenames to the model invites hallucinated summaries when the actual extracted content is thin. The model must rely solely on the document content provided below.
const WikiTaxonomyPlanPrompt = `` /* 2303-byte string literal not displayed */
WikiTaxonomyPlanPrompt assigns a directory path (category) to every entity / concept page produced by ONE ingest batch in a single call, so the whole set lands on one coherent tree that reuses existing folders — instead of each page inventing its own folders in parallel (which diverges worst on the founding batch, when the KB still has no folders to anchor on). The result is applied in reduce only to pages that don't already have a category, so user edits and previously-filed pages are never churned.
Variables ¶
This section is empty.
Functions ¶
func BuildSystemPrompt ¶
func BuildSystemPrompt( knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, systemPromptTemplate ...string, ) string
BuildSystemPrompt builds the progressive RAG system prompt This is the main function to use - it uses a unified template with dynamic web search status
func BuildSystemPromptWithOptions ¶
func BuildSystemPromptWithOptions( knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, options *BuildSystemPromptOptions, systemPromptTemplate ...string, ) string
BuildSystemPromptWithOptions builds the system prompt with additional options like skills
func GetProgressiveRAGSystemPrompt ¶
GetProgressiveRAGSystemPrompt returns the Progressive RAG Agent system prompt from config templates. The template must be defined in config/prompt_templates/agent_system_prompt.yaml with mode "rag". Returns empty string if config is nil or template not found.
func GetPureAgentSystemPrompt ¶
GetPureAgentSystemPrompt returns the Pure Agent system prompt from config templates. The template must be defined in config/prompt_templates/agent_system_prompt.yaml with mode "pure". Returns empty string if config is nil or template not found.
func HistoryAsSent ¶
HistoryAsSent is stored history as the engine sends it. Unless the agent retains retrieval history, KB and Wiki tool results from earlier turns are redacted, so the model does not reuse retrieval data the knowledge base may have outgrown. The history loader prices turns with it too, so its token budget is spent on what reaches the model, not on a wiki page that goes out as one line.
func HistoryTokenBudget ¶
func HistoryTokenBudget(cfg *types.AgentConfig) int
HistoryTokenBudget is how much stored history one run of cfg may load: the whole context window, deliberately more than the compaction threshold.
The loader drops the oldest turns that do not fit, and what it drops is lost: it is neither replayed nor summarized. With a budget equal to the threshold the loader always trimmed first, so whenever one turn was larger than the system prompt plus the new question the request never crossed the threshold, nothing was summarized, and the session became a sliding window that never got a checkpoint. Loading up to the window leaves the overflow to the first round's compaction instead, which summarizes it and persists a checkpoint. The compactor bounds its own summarizer input, so a history this large cannot make the summarization request itself overflow.
func WikiGranularityGuidance ¶
WikiGranularityGuidance returns the guidance text to inject into the WikiCandidateSlugPrompt template for the given granularity. Accepts the raw string value stored in WikiConfig.ExtractionGranularity; callers do NOT need to Normalize() first — unknown values fall through to standard.
Types ¶
type AgentEngine ¶
type AgentEngine struct {
// contains filtered or unexported fields
}
AgentEngine is the core engine for running ReAct agents.
History persistence note: the engine is stateless across turns. Conversation history is rebuilt from the DB once per turn by the caller (see service.LoadAgentHistory) and passed into Execute as llmContext. The engine therefore does not maintain its own cache, system-prompt store, or cross-turn buffer.
func NewAgentEngine ¶
func NewAgentEngine( config *types.AgentConfig, chatModel chat.Chat, toolRegistry *agenttools.ToolRegistry, eventBus *event.EventBus, knowledgeBasesInfo []*KnowledgeBaseInfo, selectedDocs []*SelectedDocumentInfo, sessionID string, systemPromptTemplate string, ) *AgentEngine
NewAgentEngine creates a new agent engine
func NewAgentEngineWithSkills ¶
func NewAgentEngineWithSkills( config *types.AgentConfig, chatModel chat.Chat, toolRegistry *agenttools.ToolRegistry, eventBus *event.EventBus, knowledgeBasesInfo []*KnowledgeBaseInfo, selectedDocs []*SelectedDocumentInfo, sessionID string, systemPromptTemplate string, skillsManager *skills.Manager, ) *AgentEngine
NewAgentEngineWithSkills creates a new agent engine with skills support
func (*AgentEngine) Execute ¶
func (e *AgentEngine) Execute( ctx context.Context, sessionID, messageID, query string, llmContext []chat.Message, imageURLs ...[]string, ) (*types.AgentState, error)
Execute executes the agent with conversation history and streaming output All events are emitted to EventBus and handled by subscribers (like Handler layer)
func (*AgentEngine) GetSkillsManager ¶
func (e *AgentEngine) GetSkillsManager() *skills.Manager
GetSkillsManager returns the skills manager
func (*AgentEngine) RenderUserTurnContent ¶
func (e *AgentEngine) RenderUserTurnContent(sessionID, query string) string
RenderUserTurnContent builds the user-turn payload for the current LLM call (runtime_context + must_use + query). Used by Execute and finalize paths only; not written to rendered_content / history.
func (*AgentEngine) SetAppConfig ¶
func (e *AgentEngine) SetAppConfig(cfg *appconfig.Config)
SetAppConfig sets the application config for prompt template resolution. This allows the engine to read default prompts from config/prompt_templates/ YAML files.
func (*AgentEngine) SetContextCheckpointSink ¶
func (e *AgentEngine) SetContextCheckpointSink(sink types.ContextCheckpointSink)
SetContextCheckpointSink enables persisting compaction checkpoints. Nil (the default) keeps every compaction local to the turn that ran it.
func (*AgentEngine) SetImageDescriber ¶
func (e *AgentEngine) SetImageDescriber(fn ImageDescriberFunc)
SetImageDescriber sets the VLM function for generating text descriptions of images in tool results. When set and the chat model cannot view images, tool result images are described while their tool call runs and the descriptions are appended to the tool message content.
func (*AgentEngine) SetMemoryPrompt ¶
func (e *AgentEngine) SetMemoryPrompt(prompt string)
SetMemoryPrompt supplies the long-term memory envelope for this run. Empty input leaves the system prompt untouched.
func (*AgentEngine) SetPinnedMentions ¶
func (e *AgentEngine) SetPinnedMentions(mcpServices []*PinnedMCPServiceInfo, skills []*PinnedSkillInfo)
SetPinnedMentions sets per-turn @mention scope for MCP services and skills.
func (*AgentEngine) SetQuestionOrigin ¶
func (e *AgentEngine) SetQuestionOrigin(origin *QuestionOriginInfo)
SetQuestionOrigin records the knowledge source of a suggested question the user picked for this turn; nil clears it.
func (*AgentEngine) SetSkillsManager ¶
func (e *AgentEngine) SetSkillsManager(manager *skills.Manager)
SetSkillsManager sets the skills manager for the engine
func (*AgentEngine) SetSteerSink ¶
func (e *AgentEngine) SetSteerSink(sink types.SteerSink)
SetSteerSink wires the optional steer channel. Nil (the default) disables mid-run injection entirely — every existing call site keeps working. The sink satisfies types.SteerSink structurally.
func (*AgentEngine) SetWorkspaceLayout ¶
func (e *AgentEngine) SetWorkspaceLayout(layout sandbox.WorkspaceLayout)
SetWorkspaceLayout injects the session's real workspace into the system prompt. Host sessions must pass the user directory so the model does not keep listing /workspace.
type BuildSystemPromptOptions ¶
type BuildSystemPromptOptions struct {
SelectedTools []string // Actual registered tools for this turn, after capability filtering
SkillsMetadata []*skills.SkillMetadata
ShellExecEnabled bool
SkillInstallMode bool
Language string // User language name for {{language}} placeholder (e.g. "Chinese (Simplified)")
Config *config.Config // Config for reading prompt templates; nil leaves the default base empty
MemoryPrompt string
ProtocolPrompt string
WorkspaceLayout sandbox.WorkspaceLayout
}
BuildSystemPromptOptions contains optional parameters for BuildSystemPrompt
type ImageDescriberFunc ¶
ImageDescriberFunc generates a text description of an image. Signature matches vlm.VLM.Predict so it can be injected without importing the vlm package.
type KnowledgeBaseInfo ¶
type KnowledgeBaseInfo struct {
ID string
Name string
Type string // Knowledge base type: "document" or "faq"
Description string
DocCount int
// Capabilities lists the retrieval surfaces this KB exposes. Any subset of
// {"wiki", "chunks"}. "chunks" is present when the KB has vector and/or
// keyword (BM25) indexing enabled. This is the *deterministic* source of
// truth the agent should consult before picking a retrieval strategy —
// significantly more reliable than running probing searches.
Capabilities []string
RecentDocs []RecentDocInfo // Recently added documents (up to 10)
// Profile is the generated description (gist, merged topics, typical
// questions) derived from document profiles. It complements the manual
// Description: that one says what the KB is for, this one says what is
// actually in it. nil when never generated.
Profile *types.KnowledgeBaseProfile
}
KnowledgeBaseInfo contains essential information about a knowledge base for agent prompt
type PinnedMCPServiceInfo ¶
type PinnedMCPServiceInfo struct {
Discoverable bool // Available through the scoped MCP directory.
ID string
Name string
Description string
ToolNames []string // Registered tool.function names for this service (mcp_{service}_{tool})
}
PinnedMCPServiceInfo describes an MCP service explicitly @mentioned for this turn.
type PinnedSkillInfo ¶
PinnedSkillInfo describes a skill explicitly @mentioned for this turn.
type PlaceholderDefinition ¶
type PlaceholderDefinition struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description"`
}
PlaceholderDefinition defines a placeholder exposed to UI/configuration Deprecated: Use types.PromptPlaceholder instead
func AvailablePlaceholders ¶
func AvailablePlaceholders() []PlaceholderDefinition
AvailablePlaceholders lists all supported prompt placeholders for UI hints This returns agent mode specific placeholders
type QuestionOriginInfo ¶
type QuestionOriginInfo struct {
KnowledgeBaseID string
KnowledgeBaseName string
Document *SelectedDocumentInfo // nil when only the base is known
}
QuestionOriginInfo is the knowledge source a suggested question was generated from, when the user picked that question. Rendered into runtime_context so the model searches the source before answering.
type RecentDocInfo ¶
type RecentDocInfo struct {
ChunkID string
KnowledgeBaseID string
KnowledgeID string
Title string
Description string
FileName string
FileSize int64
Type string
CreatedAt string // Formatted time string
FAQStandardQuestion string
FAQSimilarQuestions []string
FAQAnswers []string
}
RecentDocInfo contains brief information about a recently added document
type SelectedDocumentInfo ¶
type SelectedDocumentInfo struct {
KnowledgeID string // Knowledge ID
KnowledgeBaseID string // Knowledge base ID
Title string // Document title
FileName string // Original file name
FileType string // File type (pdf, docx, etc.)
}
SelectedDocumentInfo contains summary information about a user-selected document (via @ mention). Injected into the user message runtime_context (pinned_documents); content is fetched via tools.
type SystemPromptSection ¶
SystemPromptSection identifies the source of each effective prompt fragment. Keep runtime policy here, template content in YAML, and retrieved data in messages.
func BuildSystemPromptSections ¶
func BuildSystemPromptSections( knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, options *BuildSystemPromptOptions, systemPromptTemplate ...string, ) []SystemPromptSection
BuildSystemPromptSections is the single assembly path, also usable by diagnostics. Custom templates replace only the base section; tool scope and runtime contracts always come from the active engine, never from editable template text.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package approval implements human-in-the-loop gating for dangerous MCP tool calls (issue #1173).
|
Package approval implements human-in-the-loop gating for dangerous MCP tool calls (issue #1173). |
|
Package compaction keeps an agent turn inside the model's context window by replacing older conversation with a structured summary.
|
Package compaction keeps an agent turn inside the model's context window by replacing older conversation with a structured summary. |
|
Package skills provides Agent Skills functionality following Claude's Progressive Disclosure pattern.
|
Package skills provides Agent Skills functionality following Claude's Progressive Disclosure pattern. |
|
Package token provides token estimation for LLM context window management.
|
Package token provides token estimation for LLM context window management. |
|
Package tools — capability requirements for built-in agent tools.
|
Package tools — capability requirements for built-in agent tools. |