Documentation
¶
Index ¶
- func ContextWithSteerCh(ctx context.Context, ch <-chan SteerMessage) context.Context
- func ContextWithSteerConsumed(ctx context.Context, fn func(count int)) context.Context
- type Agent
- func (a *Agent) Close() error
- func (a *Agent) GenerateWithLoop(ctx context.Context, messages []fantasy.Message, onToolCall ToolCallHandler, ...) (*GenerateWithLoopResult, error)
- func (a *Agent) GenerateWithLoopAndStreaming(ctx context.Context, messages []fantasy.Message, onToolCall ToolCallHandler, ...) (*GenerateWithLoopResult, error)
- func (a *Agent) GetCoreToolCount() int
- func (a *Agent) GetExtensionToolCount() int
- func (a *Agent) GetLoadedServerNames() []string
- func (a *Agent) GetLoadingMessage() string
- func (a *Agent) GetMCPToolCount() int
- func (a *Agent) GetModel() fantasy.LanguageModel
- func (a *Agent) GetTools() []fantasy.AgentTool
- func (a *Agent) MCPToolsReady() bool
- func (a *Agent) SetExtraTools(extraTools []fantasy.AgentTool)
- func (a *Agent) SetModel(ctx context.Context, config *models.ProviderConfig) error
- func (a *Agent) WaitForMCPTools() error
- type AgentConfig
- type AgentCreationOptions
- type GenerateWithLoopResult
- type ReasoningCompleteHandler
- type ReasoningDeltaHandler
- type ResponseHandler
- type SpinnerFunc
- type SteerMessage
- type StepMessagesHandler
- type StepUsageHandler
- type StreamingResponseHandler
- type ToolCallContentHandler
- type ToolCallHandler
- type ToolExecutionHandler
- type ToolOutputHandler
- type ToolResultHandler
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ContextWithSteerCh ¶ added in v0.24.0
func ContextWithSteerCh(ctx context.Context, ch <-chan SteerMessage) context.Context
ContextWithSteerCh returns a new context with the steer channel attached. The agent's PrepareStep function checks this channel between steps and injects any pending steer messages as user messages before the next LLM call.
func ContextWithSteerConsumed ¶ added in v0.24.0
ContextWithSteerConsumed returns a new context with a callback that fires when steer messages are consumed by PrepareStep. The count argument is the number of messages injected in this batch.
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent represents an AI agent with core tool integration using the LLM library. Core tools (bash, read, write, edit, grep, find, ls) are registered as direct AgentTool implementations — no MCP layer, no serialization overhead. Additional tools from external MCP servers can be loaded alongside core tools.
When MCP servers are configured, tool loading happens in the background so the agent (and UI) can start immediately. The first LLM call automatically waits for MCP tools to finish loading before proceeding.
func CreateAgent ¶
func CreateAgent(ctx context.Context, opts *AgentCreationOptions) (*Agent, error)
CreateAgent creates an agent with optional spinner for Ollama models. It shows a loading spinner for Ollama models if ShowSpinner is true and not in quiet mode. Returns the created agent or an error if creation fails.
func NewAgent ¶
func NewAgent(ctx context.Context, agentConfig *AgentConfig) (*Agent, error)
NewAgent creates a new Agent with core tools and optional MCP tool integration. Core tools (bash, read, write, edit, grep, find, ls) are always registered. If MCP servers are configured, their tools are loaded in the background — the agent returns immediately and is usable with core tools only. The first LLM call (GenerateWithLoop) automatically waits for MCP tools to finish loading and rebuilds the agent with the full tool set.
func (*Agent) Close ¶
Close closes the agent and cleans up resources. If MCP tools are still loading in the background, Close waits for them to finish before closing connections to avoid resource leaks.
func (*Agent) GenerateWithLoop ¶
func (a *Agent) GenerateWithLoop(ctx context.Context, messages []fantasy.Message, onToolCall ToolCallHandler, onToolExecution ToolExecutionHandler, onToolResult ToolResultHandler, onResponse ResponseHandler, onToolCallContent ToolCallContentHandler, ) (*GenerateWithLoopResult, error)
GenerateWithLoop processes messages with a custom loop that displays tool calls in real-time.
func (*Agent) GenerateWithLoopAndStreaming ¶
func (a *Agent) GenerateWithLoopAndStreaming(ctx context.Context, messages []fantasy.Message, onToolCall ToolCallHandler, onToolExecution ToolExecutionHandler, onToolResult ToolResultHandler, onResponse ResponseHandler, onToolCallContent ToolCallContentHandler, onStreamingResponse StreamingResponseHandler, onReasoningDelta ReasoningDeltaHandler, onReasoningComplete ReasoningCompleteHandler, onToolOutput ToolOutputHandler, onStepMessages StepMessagesHandler, onStepUsage StepUsageHandler, ) (*GenerateWithLoopResult, error)
GenerateWithLoopAndStreaming processes messages using the agent with streaming and callbacks. The agent handles the tool call loop internally. We map the rich callback system to kit's existing callback interface for UI integration.
func (*Agent) GetCoreToolCount ¶ added in v0.3.0
GetCoreToolCount returns the number of core tools.
func (*Agent) GetExtensionToolCount ¶
GetExtensionToolCount returns the number of tools registered by extensions.
func (*Agent) GetLoadedServerNames ¶
GetLoadedServerNames returns the names of successfully loaded MCP servers.
func (*Agent) GetLoadingMessage ¶
GetLoadingMessage returns the loading message from provider creation.
func (*Agent) GetMCPToolCount ¶
GetMCPToolCount returns the number of tools loaded from external MCP servers.
func (*Agent) GetModel ¶
func (a *Agent) GetModel() fantasy.LanguageModel
GetModel returns the underlying LanguageModel.
func (*Agent) GetTools ¶
GetTools returns the list of available tools loaded in the agent, including core tools, MCP tools, and extension-registered tools.
func (*Agent) MCPToolsReady ¶ added in v0.41.0
MCPToolsReady returns true if MCP tool loading has completed (or was never started). This is a non-blocking check useful for UI status display.
func (*Agent) SetExtraTools ¶ added in v0.35.0
SetExtraTools replaces the agent's extra tools (e.g. extension-registered tools) and rebuilds the internal agent with the updated tool list. The model, system prompt, and all other configuration are preserved.
func (*Agent) SetModel ¶ added in v0.3.0
SetModel swaps the agent's LLM provider to a new model. The existing tools, system prompt, and configuration are preserved. The old provider is closed if it has a closer. Returns the previous model string for notification.
func (*Agent) WaitForMCPTools ¶ added in v0.41.0
WaitForMCPTools blocks until background MCP tool loading completes. Returns nil if no MCP servers are configured or if loading succeeded. Returns the loading error if all servers failed. Safe to call multiple times.
type AgentConfig ¶
type AgentConfig struct {
ModelConfig *models.ProviderConfig
MCPConfig *config.Config
SystemPrompt string
MaxSteps int
StreamingEnabled bool
DebugLogger tools.DebugLogger
// AuthHandler handles OAuth authorization for remote MCP servers.
// When set, remote transports are configured with OAuth support.
// If nil, remote MCP servers that require OAuth will fail to connect.
AuthHandler tools.MCPAuthHandler
// CoreTools overrides the default core tool set. If empty, core.AllTools()
// is used. This allows SDK users to provide a custom tool set (e.g.
// CodingTools or tools with a custom WorkDir).
CoreTools []fantasy.AgentTool
// DisableCoreTools, when true, prevents loading any core tools.
// If both DisableCoreTools is true and CoreTools is empty, the agent
// will have no tools (useful for simple chat completions).
DisableCoreTools bool
// ToolWrapper is an optional function that wraps the combined tool list
// before it is passed to the LLM agent. Used by the extensions system
// to intercept tool calls/results.
ToolWrapper func([]fantasy.AgentTool) []fantasy.AgentTool
// ExtraTools are additional tools to include alongside core and MCP tools.
// Used by extensions to register custom tools.
ExtraTools []fantasy.AgentTool
// OnMCPServerLoaded, if non-nil, is called when each MCP server finishes
// loading (successfully or with error). The callback receives the server
// name, tool count, and any error. Called from the background goroutine.
OnMCPServerLoaded func(serverName string, toolCount int, err error)
}
AgentConfig holds configuration options for creating a new Agent.
type AgentCreationOptions ¶
type AgentCreationOptions struct {
// ModelConfig specifies the LLM provider and model to use
ModelConfig *models.ProviderConfig
// MCPConfig contains MCP server configurations
MCPConfig *config.Config
// SystemPrompt is the initial system message for the agent
SystemPrompt string
// MaxSteps limits the number of tool calls (0 for unlimited)
MaxSteps int
// StreamingEnabled controls whether responses are streamed
StreamingEnabled bool
// ShowSpinner indicates whether to show a spinner for Ollama models during loading
ShowSpinner bool // For Ollama models
// Quiet suppresses the spinner even if ShowSpinner is true
Quiet bool // Skip spinner if quiet
// SpinnerFunc is the function to show spinner, provided by the caller
SpinnerFunc SpinnerFunc // Function to show spinner (provided by caller)
// DebugLogger is an optional logger for debugging MCP communications
DebugLogger tools.DebugLogger // Optional debug logger
// AuthHandler handles OAuth authorization for remote MCP servers
AuthHandler tools.MCPAuthHandler
// CoreTools overrides the default core tool set. If empty, core.AllTools()
// is used.
CoreTools []fantasy.AgentTool
// DisableCoreTools, when true, prevents loading any core tools.
// If both DisableCoreTools is true and CoreTools is empty, the agent
// will have no tools (useful for simple chat completions).
DisableCoreTools bool
// ToolWrapper wraps the combined tool list before agent creation.
ToolWrapper func([]fantasy.AgentTool) []fantasy.AgentTool
// ExtraTools are additional tools to include (e.g. from extensions).
ExtraTools []fantasy.AgentTool
// OnMCPServerLoaded, if non-nil, is called when each MCP server finishes
// loading (successfully or with error). Called from the background goroutine.
OnMCPServerLoaded func(serverName string, toolCount int, err error)
}
AgentCreationOptions contains options for creating an agent. It extends AgentConfig with UI-related options for showing progress during creation.
type GenerateWithLoopResult ¶
type GenerateWithLoopResult struct {
// FinalResponse is the last message generated by the model
FinalResponse *fantasy.Response
// ConversationMessages contains all messages in the conversation including tool calls and results
ConversationMessages []fantasy.Message
// Messages contains the conversation as custom content blocks
Messages []message.Message
// TotalUsage contains aggregate token usage across all steps
TotalUsage fantasy.Usage
// StopReason is the LLM provider's finish reason for the final response.
StopReason string
// PersistedMessageCount is the number of new messages (beyond the original
// input) that were already persisted incrementally via OnStepMessages during
// generation. The caller should skip these when doing post-generation
// persistence to avoid duplicates.
PersistedMessageCount int
}
GenerateWithLoopResult contains the result and conversation history from an agent interaction.
type ReasoningCompleteHandler ¶ added in v0.35.0
type ReasoningCompleteHandler func()
ReasoningCompleteHandler is a function type for handling reasoning/thinking completion. Called when the last reasoning token has been processed, before text streaming starts.
type ReasoningDeltaHandler ¶ added in v0.7.0
type ReasoningDeltaHandler func(delta string)
ReasoningDeltaHandler is a function type for handling streaming reasoning/thinking deltas.
type ResponseHandler ¶
type ResponseHandler func(content string)
ResponseHandler is a function type for handling LLM responses.
type SpinnerFunc ¶
SpinnerFunc is a function type for showing spinners during agent creation. It executes the provided function while displaying an animated spinner.
type SteerMessage ¶ added in v0.36.0
SteerMessage carries a steering prompt and optional file attachments (e.g. clipboard images) through the steer channel.
type StepMessagesHandler ¶ added in v0.44.0
StepMessagesHandler is a function type for persisting messages after each complete step in a multi-step agent turn. The handler receives the messages produced by the step (typically an assistant message with tool calls followed by a tool-role message with results, or a final assistant message with text). This enables incremental session persistence so that progress is saved as it happens rather than only at the end of the turn.
type StepUsageHandler ¶ added in v0.23.0
type StepUsageHandler func(inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens int64)
StepUsageHandler is a function type for handling token usage after each complete step in a multi-step agent turn. This enables real-time cost tracking during long-running tool-calling conversations.
type StreamingResponseHandler ¶
type StreamingResponseHandler func(content string)
StreamingResponseHandler is a function type for handling streaming LLM responses.
type ToolCallContentHandler ¶
type ToolCallContentHandler func(content string)
ToolCallContentHandler is a function type for handling content that accompanies tool calls.
type ToolCallHandler ¶
type ToolCallHandler func(toolCallID, toolName, toolArgs string)
ToolCallHandler is a function type for handling tool calls as they happen.
type ToolExecutionHandler ¶
ToolExecutionHandler is a function type for handling tool execution start/end events.
type ToolOutputHandler ¶ added in v0.20.0
type ToolOutputHandler = core.ToolOutputCallback
ToolOutputHandler is a function type for handling streaming tool output chunks. Used by tools like bash to stream output as it arrives rather than waiting for the command to complete. The isStderr flag indicates if the chunk contains stderr output. Note: This is an alias for core.ToolOutputCallback to avoid import cycles.
type ToolResultHandler ¶
ToolResultHandler is a function type for handling tool results. The metadata parameter carries optional structured data (e.g. file diff info) from the tool execution, JSON-encoded. It may be empty.