instruction_processor.go

Overview

This file implements dynamic processing and injection of instructions for large language model (LLM) agents by replacing placeholders in instruction templates with runtime session state values or artifact contents. It supports both agent-specific and global instructions, enabling context-aware prompt construction for LLM requests.

The core functionality revolves around parsing instruction templates for placeholders enclosed in curly braces (e.g., {user_name}, {app:current_task}, {artifact.report}), validating these placeholders, retrieving corresponding values from session state or artifact storage, and injecting these values into the instructions before appending them to the LLM request.

This mechanism enables AI agents to deliver personalized, dynamic, and contextually relevant instructions to the LLM, adapting to the current invocation context and session state.

The file is part of the broader Instruction Template Processing (80563) and Session State Injection (80597) domains, and tightly integrates with LLM Integration and Agents (80562), Session Management (80559), and Artifact Management (80557).


Key Components

Constants


Function: instructionsRequestProcessor

func instructionsRequestProcessor(ctx agent.InvocationContext, req *model.LLMRequest) error

Purpose:
Main entry point to process and append instructions to an LLM request during agent invocation.

Parameters:

Returns:
Error if instruction processing or appending fails; otherwise nil.

Behavior:

Usage Example:

Typically invoked as part of the agent lifecycle before making an LLM call, ensuring instructions are up-to-date with session state.


Functions: appendInstructions and appendGlobalInstructions

func appendInstructions(ctx agent.InvocationContext, req *model.LLMRequest, agentState *State) error
func appendGlobalInstructions(ctx agent.InvocationContext, req *model.LLMRequest, agentState *State) error

Purpose:
Inject processed instructions into the LLM request, either agent-specific or global.

Parameters:

Returns:
Error on failure to evaluate or inject instructions.

Behavior:

Implementation Detail:


Function: InjectSessionState

func InjectSessionState(ctx agent.InvocationContext, template string) (string, error)

Purpose:
Core logic to parse an instruction template and replace placeholders with actual session state or artifact data.

Parameters:

Returns:
Processed instruction string with placeholders replaced, or error if any required value is missing or retrieval fails.

Behavior:

Usage Example:

injected, err := InjectSessionState(ctx, "Hello {user_name}, see {artifact.report}")
if err != nil {
    // handle error
}
// injected now contains the instruction with placeholders replaced

Function: replaceMatch

func replaceMatch(ctx agent.InvocationContext, match string) (string, error)

Purpose:
Resolves a single placeholder match by fetching its corresponding value from session state or artifact storage.

Parameters:

Returns:
Replacement string or error if resolution fails.

Implementation Details:

Error Handling:


Helper Functions: isIdentifier and isValidStateName

func isIdentifier(s string) bool
func isValidStateName(varName string) bool

Purpose:
Validate if strings conform to acceptable Go-like identifier rules and namespace prefix conventions.

isIdentifier checks if a string starts with a letter or underscore and contains only letters, digits, or underscores.

isValidStateName additionally allows a single colon-separated prefix if it matches one of recognized prefixes (app:, user:, temp:), and validates the suffix as an identifier.


Important Implementation Details and Algorithms


Interaction with Other System Components


Structure Diagram

classDiagram
class InstructionProcessor {
+instructionsRequestProcessor(ctx, req) error
+appendInstructions(ctx, req, agentState) error
+appendGlobalInstructions(ctx, req, agentState) error
+InjectSessionState(ctx, template) (string, error)
-replaceMatch(ctx, match) (string, error)
-isIdentifier(s) bool
-isValidStateName(varName) bool
}
InstructionProcessor ..> agent.InvocationContext
InstructionProcessor ..> model.LLMRequest
InstructionProcessor ..> State
InstructionProcessor ..> ArtifactService
InstructionProcessor ..> SessionState

Workflow Diagram: Instruction Injection Process

flowchart TD
Start[Start: Instruction Template]
Parse[Parse Template for Placeholders]
ForEach[For Each Placeholder]
IsArtifact{Is Placeholder an Artifact?}
LoadArtifact[Load Artifact Content]
GetState[Get Session State Value]
IsOptional{Is Placeholder Optional?}
Replace[Replace Placeholder with Value]
Error{Error?}
SkipOrFail[Skip or Fail Based on Optional Flag]
End[Return Processed Instruction String]
Start --> Parse --> ForEach
ForEach --> IsArtifact
IsArtifact -->|Yes| LoadArtifact
IsArtifact -->|No| GetState
LoadArtifact --> Error
GetState --> Error
Error -->|Yes| SkipOrFail
Error -->|No| Replace
SkipOrFail --> ForEach
Replace --> ForEach
ForEach -->|No More Placeholders| End

This flowchart illustrates how the file processes an instruction template by iterating over placeholders, resolving each either from artifact content or session state, handling optional placeholders gracefully, and reconstructing the final instruction string.


Usage Pattern Summary


This file is a critical component for dynamic prompt generation, ensuring that instructions sent to LLMs are contextually accurate and up-to-date with session and artifact data, enhancing the intelligence and responsiveness of AI agents.