console.go
Overview
The console.go file provides a console-based launcher to interact with an AI agent in a command-line interface (CLI) environment. It enables users to input text queries directly via the console and receive responses streamed from the agent. This file implements a sub-launcher adhering to the common launcher interface used across the system, allowing for integration with the broader agent framework and session management services.
The main purpose is to facilitate simple, interactive user-agent conversations without requiring a graphical interface or web server, making it suitable for quick testing, debugging, or lightweight deployments.
Types and Their Responsibilities
1. consoleConfig
Holds configuration options parsed from command-line flags specific to the console launcher.
Fields:
streamingMode agent.StreamingMode
Enum indicating how agent responses are streamed back to the user (e.g., Server-Sent Events or none).streamingModeString string
Raw string from CLI arguments to be converted to theStreamingModeenum.
2. consoleLauncher
Implements the launcher.SubLauncher interface and encapsulates the interactive console logic.
Fields:
flags *flag.FlagSet
Flag set used to parse command-line arguments for the console launcher.config *consoleConfig
Stores parsed configuration values.
Functions and Methods
NewLauncher() launcher.SubLauncher
Purpose:
Factory function to create a new instance ofconsoleLauncherwith initialized flags for parsing.Details:
Defines thestreaming_modeflag with default value agent.StreamingModeSSE and valid optionsnoneorsse.Returns:
A launcher.SubLauncher instance configured for console interaction.Usage Example:
launcher := console.NewLauncher()
(l *consoleLauncher) Parse(args []string) ([]string, error)
Purpose:
Parses the command-line arguments specific to the console launcher.Parameters:
args []string- Arguments to parse.
Returns:
Remaining unparsed arguments after console-specific flags are processed.
Error if parsing fails or invalid flag values are provided.
Implementation Details:
Converts thestreaming_modestring to its corresponding enum and validates it. Accepts onlynoneorsse.
(l *consoleLauncher) Run(ctx context.Context, config *launcher.Config) error
Purpose:
Starts the main interaction loop that reads user input from the console, sends it to the agent, and streams back the agent's response.Parameters:
ctx context.Context- Context for cancellation and deadlines.config *launcher.Config- Configuration including agent loader, session service, artifact service.
Returns:
Error if session creation or runner setup fails; otherwise runs indefinitely until terminated.
Detailed Workflow:
Creates or retrieves a user session using the provided session service.
Instantiates a
runner.Runnerto execute the agent with the session.Reads user input line-by-line from standard input.
Sends user input as a message (
genai.Content) to the agent runner.Streams back the agent's response incrementally or in full, depending on the streaming mode.
Handles errors during agent execution gracefully by printing error messages.
Streaming Modes:
SSE (Server-Sent Events): Prints partial response chunks as they arrive.
None: Prints the entire response at once.
Usage Example:
err := launcher.Run(ctx, config) if err != nil { log.Fatal(err) }
(l *consoleLauncher) Keyword() string
Purpose:
Returns the CLI keywordconsoleused to identify this sub-launcher.
(l *consoleLauncher) CommandLineSyntax() string
Purpose:
Returns the formatted command-line flag usage string for this launcher, leveraging utility functions.
(l *consoleLauncher) SimpleDescription() string
Purpose:
Provides a concise description:"runs an agent in console mode."
(l *consoleLauncher) Execute(ctx context.Context, config *launcher.Config, args []string) error
Purpose:
Convenience method that parses CLI arguments, validates no extra unknown arguments remain, and runs the console launcher.Parameters:
ctx context.Contextconfig *launcher.Configargs []string- CLI arguments
Returns:
Error if argument parsing or execution fails.
Implementation Detail:
CallsParse(), checks for unparsed arguments viauniversal.ErrorOnUnparsedArgs(), then callsRun().
Important Implementation Details and Algorithms
Session Management:
Uses a session service (sessionService) to create and maintain a session per user interaction. Defaults to an in-memory session if none provided.Agent Execution:
Therunnerpackage coordinates sending user input to the root agent and managing the streaming of responses. This isolates the console launcher from agent internals.Streaming Logic:
The console launcher supports two streaming modes, SSE and none, to control how partial responses are printed. It maintains a bufferprevTextto avoid duplicate output when streaming.Command-Line Parsing:
Uses Go'sflag.FlagSetto define and parse CLI flags specific to the console launcher, separating concerns from other launchers.Error Handling:
Provides user-friendly error messages on session creation or agent running failure, and logs fatal errors on I/O issues.
Interaction with Other System Components
Agent Loading:
Obtains the root agent from the providedlauncher.Config'sAgentLoader.Session Service:
Interfaces withsession.Serviceto create and manage user sessions, enabling stateful conversations.Runner:
Usesrunner.Runnerto handle the actual agent execution and message streaming, which internally manages agent invocation context and event processing as described in Agent Invocation Context and Agent Execution Runner.Command-Line Utilities:
Utilizesutil.FormatFlagUsagefor CLI help text formatting anduniversal.ErrorOnUnparsedArgsfor argument validation.
Console Launcher Structure Diagram
classDiagram
class consoleLauncher {
-flags: FlagSet
-config: consoleConfig
+Parse(args)
+Run(ctx, config)
+Keyword()
+CommandLineSyntax()
+SimpleDescription()
+Execute(ctx, config, args)
}
class consoleConfig {
-streamingMode: StreamingMode
-streamingModeString: string
}
consoleLauncher --> consoleConfig
Usage Scenario Example
In a command-line environment, a user can invoke this launcher with:
myapp console --streaming_mode=sse
The launcher reads input lines from the console, sends them to the AI agent, and outputs the streaming responses directly below the prompt, allowing real-time conversational interaction.
This file is a critical part of the overall system enabling direct console-based interaction with agents, leveraging session management and agent execution infrastructure described in Session Management and Agent Execution Runner.