instruction.go
Overview
The instruction.go file provides a utility function to perform session state injection into instruction templates used by AI agents. Its primary purpose is to process textual instruction templates containing placeholders and replace them dynamically with relevant runtime data from the session state or artifact contents.
This injection mechanism enables large language model (LLM) agents to receive contextually enriched prompts personalized to the current session, improving interaction quality and relevance. The function exposed here, InjectSessionState, acts as a safe wrapper that verifies the context type and delegates the actual injection work to an internal implementation.
The file is part of the Instruction Injection and Session State Injection functionality within the system, interfacing primarily with agent invocation contexts, session state management, and artifact services to resolve placeholders in templates.
Function: InjectSessionState
func InjectSessionState(ctx agent.ReadonlyContext, template string) (string, error)
Purpose
Processes an instruction template string by injecting values from session state and artifacts, replacing placeholders of the form {key_name} or {artifact.key_name} with their corresponding runtime values.
Parameters
ctx agent.ReadonlyContext
A read-only agent invocation context providing access to session state and artifact services. This context must be of type*icontext.ReadonlyContextinternally; otherwise, an error is returned.template string
The instruction template containing zero or more placeholders to be resolved and replaced.
Returns
(string, error)
The fully injected instruction string with all placeholders replaced by their resolved values, or an error if injection fails due to invalid context type or missing/invalid placeholders.
Usage Example
injectedInstruction, err := instructionutil.InjectSessionState(ctx, "Hello {user_name}, see report {artifact.report}.")
if err != nil {
// handle error, e.g. missing session variable or artifact
}
fmt.Println(injectedInstruction)
// Output might be: "Hello Alice, see report <contents of report artifact>."
Behavior Details
The function casts the given
ReadonlyContextto the internal*icontext.ReadonlyContexttype to access the underlying invocation context.It calls the internal API
llminternal.InjectSessionStatewith the invocation context and template string.The internal function performs placeholder parsing and replacement:
Placeholders matching
{key_name}are replaced with session state values.Placeholders matching
{artifact.key_name}are replaced with the textual content of the specified artifact.Optional placeholders (marked by a trailing
?like{var?}) suppress errors if missing and inject empty strings.
If the context type is unexpected or injection fails, an error is returned.
Important Implementation Details
Context Type Enforcement:
By requiringagent.ReadonlyContextand internally asserting it to*icontext.ReadonlyContext, this function guarantees that only read-only contexts are used for injection, ensuring no side effects or state mutations occur during template processing.Delegation to Internal Logic:
Actual placeholder replacement logic resides in thellminternalpackage (llminternal.InjectSessionState), allowing separation of public API and internal implementation. This keeps the utility function simple and focused.Error Propagation:
Errors from invalid context types, missing session state variables, or missing artifact contents (unless optional) are propagated to the caller, enabling robust error handling upstream.Placeholder Syntax Support:
Supports placeholders with the following formats:{key_name}: Inject session variable.{artifact.key_name}: Inject artifact content.Optional placeholders with
?suffix to ignore missing keys.
Interaction with Other System Components
Invocation Context (
agent.ReadonlyContext/icontext.ReadonlyContext):
Provides access to session state and artifact services necessary for resolving placeholders.Session Management ([80559]):
Supplies session state variables referenced by placeholders.Artifact Management ([80557]):
Enables loading of artifact content referenced in templates.LLM Instruction Processing ([80563], [80568]):
This function is a core utility used by instruction providers to generate final prompt instructions with dynamic data injection before sending to the LLM.Agent Execution Pipeline:
Used within agent instruction providers and global instruction handlers to ensure instructions reflect the current session context.
Mermaid Diagram: Function Workflow
flowchart TD
Start[Start: Call InjectSessionState]
CheckCtx[Check context type]
FailCtx[Return error: invalid context type]
CallInternal[Call llminternal.InjectSessionState]
ReturnRes[Return injected instruction or error]
Start --> CheckCtx
CheckCtx -- Valid --> CallInternal
CheckCtx -- Invalid --> FailCtx
CallInternal --> ReturnRes
This diagram depicts the simple workflow of InjectSessionState: it verifies the context type, calls the internal injection method, and returns the injected string or an error.
Summary of File Role
Acts as a public-facing utility for injecting dynamic session and artifact data into instruction templates.
Enforces read-only context usage to prevent unintended mutations.
Delegates core injection logic to internal packages maintaining modularity.
Supports advanced placeholder syntax including optional keys and artifact references.
Serves as a foundational piece of the Instruction Injection subsystem enabling context-aware LLM prompts.
References to Related Topics
See Instruction Injection for the detailed mechanism of placeholder parsing and replacement algorithms used internally.
For session state data structure and retrieval, refer to Session Management.
Artifact loading and content retrieval are described in Artifact Management.
The role of instruction injection in the overall LLM agent workflow is discussed in LLM Integration and Agents.
This file is a critical utility that bridges session and artifact data with instruction templates, enabling AI agents to generate context-sensitive prompts dynamically.