common

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2026 License: BSD-3-Clause Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SkillDefaultFolder = "skills"
	SkillMainFile      = "SKILL.md"
)

Variables

View Source
var AgentGenerateInterimPromptTemplate = buildAgentGenerateInterimPrompt("%s", "%s", "%s")

AgentGenerateInterimPromptTemplate summarizes the current execution state. Its formatting arguments are the previous interim answer, user input, and serialized steps.

View Source
var ReachMaxStepConcludeTemplate = buildReachMaxStepConcludePrompt("%s", "%s", "%s")

ReachMaxStepConcludeTemplate builds a final-answer prompt after the agent reaches its maximum number of steps. Its formatting arguments are the interim result, user input, and serialized internal steps.

View Source
var StepConcludePromptTemplate = buildStepConcludePrompt("%s", "%s")

StepConcludePromptTemplate summarizes one agent step. Its formatting arguments are the user's goal and the serialized step.

Functions

func AssistantTextBlock

func AssistantTextBlock(text string) *schema.ContentBlock

func AssistantTextMessage

func AssistantTextMessage(text string) *schema.AgenticMessage

func Base64ImageBlock

func Base64ImageBlock(mimeType, base64Data string) *schema.ContentBlock

func BinaryImageBlock

func BinaryImageBlock(mimeType string, data []byte) *schema.ContentBlock

func CloneAgenticMessages

func CloneAgenticMessages(messages []*schema.AgenticMessage) []*schema.AgenticMessage

func ConsumeInterruptSignal

func ConsumeInterruptSignal(ac *AgentContext) bool

ConsumeInterruptSignal reports whether the current agent loop should stop before the next Think call. The signal is consumed when read.

func ExtractSkillHeader

func ExtractSkillHeader(text string) (string, bool)

func FillCompleteGenerateInterimPrompt

func FillCompleteGenerateInterimPrompt(interim string, userInput AgentUserInput, steps []*Step) string

func FillCompleteReachMaxStepConcludePrompt

func FillCompleteReachMaxStepConcludePrompt(interim string, userInput AgentUserInput, steps []*Step, specialRequirements []string) string

func FillStepConcludePromptTemplate

func FillStepConcludePromptTemplate(goal AgentUserInput, step *Step) string

func FunctionToolResultMessage

func FunctionToolResultMessage(result *schema.FunctionToolResult) *schema.AgenticMessage

func ImageURLBlock

func ImageURLBlock(url string) *schema.ContentBlock

func ImageURLWithDetailBlock

func ImageURLWithDetailBlock(url, detail string) *schema.ContentBlock

func NewToolParameters

func NewToolParameters(props ...ToolProperty) map[string]any

NewToolParameters creates a JSON Schema object from a list of properties.

Example:

params := NewToolParameters(
	ToolProperty{
		Name:        "users",
		Type:        "array",
		Required:    true,
		Description: "user list",
		Items: &ToolProperty{
			Type: "object",
			Properties: []ToolProperty{
				{
					Name:        "name",
					Type:        "string",
					Required:    true,
					Description: "user name",
				},
				{
					Name:        "age",
					Type:        "integer",
					Description: "user age",
				},
			},
		},
	},
)

func ReasoningBlock

func ReasoningBlock(text string) *schema.ContentBlock

func SanitizeToolName

func SanitizeToolName(name string) string

SanitizeToolName ensures tool names are compatible with LLM tool name rules: ^[a-zA-Z0-9_\\.-]+$

func TextBlock

func TextBlock(text string) *schema.ContentBlock

func TextMessage

func TextMessage(role schema.AgenticRoleType, text string) *schema.AgenticMessage

Types

type Agent

type Agent interface {
	// Do stores the current user input, starts the agent loop asynchronously,
	// and returns the context UID and the step stream for this run. The stream is
	// closed when the run finishes, is interrupted, or stops with an error.
	Do(context.Context, *AgentDoArgs, ...model.Option) (ContextUID, streaming.Stream[*Step], error)

	// Steer queues one or more user messages for a conversation. Messages are
	// committed after the next complete non-final turn. A final answer discards
	// pending messages, and steering a finalized conversation returns an error.
	Steer(context.Context, *AgentSteerArgs) error
}

type AgentContext

type AgentContext struct {
	context.Context
	// contains filtered or unexported fields
}

func NewAgentContext

func NewAgentContext(ctx context.Context) *AgentContext

func (*AgentContext) DeleteMeta

func (ac *AgentContext) DeleteMeta(key AgentDoMetaKey)

func (*AgentContext) GetAllMeta

func (ac *AgentContext) GetAllMeta() map[AgentDoMetaKey]any

func (*AgentContext) GetMeta

func (ac *AgentContext) GetMeta(key AgentDoMetaKey) any

func (*AgentContext) SetMeta

func (ac *AgentContext) SetMeta(key AgentDoMetaKey, value any)

type AgentDoArgs

type AgentDoArgs struct {
	UserInput AgentUserInput
	// ContextUID is the unique identifier for a conversation.
	// If set, the agent will load its managed context to continue thinking.
	ContextUID ContextUID
	// SpecialRequirements will be appended to the system prompt and also used in final answer generation
	SpecialRequirements []string
	// Compress decides whether to compress the steps when context exceeds the limit
	Compress bool
	// CompressionOptions configures context compression for this run.
	CompressionOptions CompressionOptions
	// ContextMeta stores stateless context meta
	ContextMeta map[AgentDoMetaKey]any
	// the max step to run the agent
	MaxStep int
	// Callbacks contains the callbacks for the agent execution
	Callbacks *Callbacks
	// SkillUsageInstruction is the instruction to guide the agent on how to use skills
	SkillUsageInstruction string
	// PlanUsageInstruction guides the React agent on when to create a plan and how granular the plan should be.
	// It is only used when EnablePlanning is true.
	PlanUsageInstruction string
	// FinalAnswerStreamingFunc receives streamed final-answer chunks.
	FinalAnswerStreamingFunc FinalAnswerStreamFn
	// FinalAnswerWebhook sends the settled final answer payload to the configured URL after the final step is stored
	FinalAnswerWebhook *FinalAnswerWebhookConfig
	// EnablePlanning enables planning tools during execution so the agent can create and update a plan while completing the task.
	EnablePlanning bool
	// ToolExecutionOptions configures how the agent executes tools, it is only used when EnablePlanning is true.
	ToolExecutionOptions *ToolExecutionOptions
}

type AgentDoMetaKey

type AgentDoMetaKey string
const (
	InternalToolPlanMetaKey AgentDoMetaKey = "current_plan"
)

func (AgentDoMetaKey) String

func (admk AgentDoMetaKey) String() string

type AgentSteerArgs

type AgentSteerArgs struct {
	// ContextUID identifies the conversation whose pending inbox receives the
	// messages.
	ContextUID ContextUID
	// UserInputs are queued as separate user messages in the supplied order.
	UserInputs []AgentUserInput
}

type AgentUsage

type AgentUsage struct {
	PromptTokens     int
	CachedTokens     int
	CompletionTokens int
}

func NewAgentUsage

func NewAgentUsage(promptTokens, cachedTokens, completionTokens int) *AgentUsage

func (*AgentUsage) Add

func (u *AgentUsage) Add(other *AgentUsage)

func (*AgentUsage) Clone

func (u *AgentUsage) Clone() *AgentUsage

type AgentUserInput

type AgentUserInput struct {
	Text   string
	Images []*schema.ContentBlock
}

func (AgentUserInput) String

func (u AgentUserInput) String() string

type CallbackFn

type CallbackFn func(*AgentContext, *Step)

type Callbacks

type Callbacks struct {
	BeforeToolExecution CallbackFn
	AfterToolExecution  CallbackFn
}

type CompressionOptions

type CompressionOptions struct {
	// Strategy selects the compaction algorithm.
	Strategy CompressionStrategy
	// RecentMessages overrides the number of raw recent messages retained.
	RecentMessages int
}

CompressionOptions configures context compression for a single agent run.

type CompressionStrategy

type CompressionStrategy string

CompressionStrategy controls the fidelity and compression ratio of context compaction.

const (
	// CompressionStrategyPrecise checkpoints older detailed tool-process messages and preserves exact references.
	// System messages, user inputs, final answers, and skill-loading/reading messages remain raw.
	CompressionStrategyPrecise CompressionStrategy = "precise"
	// CompressionStrategyAggressive summarizes older detailed tool-process messages and retains recent context.
	// System messages, user inputs, final answers, and skill-loading/reading messages remain raw.
	CompressionStrategyAggressive CompressionStrategy = "aggressive"
	// CompressionStrategyDiscardHalf discards the oldest half of detailed tool-process messages without calling the model.
	// System messages, user inputs, final answers, and skill-loading/reading messages are preserved.
	CompressionStrategyDiscardHalf CompressionStrategy = "discard_half"
)

type ContextUID

type ContextUID string

ContextUID uniquely identifies a managed conversation.

func (ContextUID) String

func (id ContextUID) String() string

type DefaultTool

type DefaultTool struct {
	ToolName        string `json:"tool_name"`
	ToolDescription string `json:"tool_description"`
	// ToolParameters stores the JSON Schema for tool parameters (required by LLM APIs)
	// Must be in format: {"type": "object", "properties": {...}, "required": [...]}
	ToolParameters ToolParameters                                 `json:"tool_parameters"`
	F              func(*AgentContext, map[string]any) ToolResult `json:"-"`
}

func NewDefaultTool

func NewDefaultTool(
	toolName,
	toolDescription string,
	toolParameters map[string]any,
	f func(*AgentContext, map[string]any) ToolResult,
) *DefaultTool

func (*DefaultTool) AddProperty

func (t *DefaultTool) AddProperty(name string, propType string, required bool)

AddProperty adds a top-level property to the tool's parameters schema.

func (*DefaultTool) Description

func (t *DefaultTool) Description() string

func (*DefaultTool) Execute

func (t *DefaultTool) Execute(ctx *AgentContext, inputs map[string]any) ToolResult

func (*DefaultTool) Name

func (t *DefaultTool) Name() string

func (*DefaultTool) Parameters

func (t *DefaultTool) Parameters() ToolParameters

func (*DefaultTool) SetParameters

func (t *DefaultTool) SetParameters(params map[string]any)

SetParameters sets the JSON Schema parameters for the tool

func (*DefaultTool) String

func (t *DefaultTool) String() string

type DefaultToolResult

type DefaultToolResult struct {
	Result string `json:"result"`
}

func NewDefaultToolResult

func NewDefaultToolResult(result string) *DefaultToolResult

func (*DefaultToolResult) ImageParts

func (d *DefaultToolResult) ImageParts() []*schema.ContentBlock

func (*DefaultToolResult) String

func (d *DefaultToolResult) String() string

type FinalAnswerStreamFn

type FinalAnswerStreamFn func(context.Context, []byte) error

type FinalAnswerWebhookConfig

type FinalAnswerWebhookConfig struct {
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
	Timeout time.Duration     `json:"timeout,omitempty"`
}

type FinalAnswerWebhookPayload

type FinalAnswerWebhookPayload struct {
	Event       string     `json:"event"`
	Agent       string     `json:"agent"`
	ContextUID  ContextUID `json:"context_uid"`
	UserInput   string     `json:"user_input"`
	FinalAnswer string     `json:"final_answer"`
	Steps       []*Step    `json:"steps,omitempty"`
	GeneratedAt time.Time  `json:"generated_at"`
}

type MCPTool

type MCPTool struct {
	MCPClient       client.MCPClient
	ToolName        string
	ToolDescription string
	ToolParameters  map[string]any
}

MCPTool adapts an MCP tool to the agent/common.Tool interface. It lets the agent call MCP tools the same way as local tools.

func (*MCPTool) Description

func (t *MCPTool) Description() string

func (*MCPTool) Execute

func (t *MCPTool) Execute(ctx *AgentContext, inputs map[string]any) ToolResult

func (*MCPTool) Name

func (t *MCPTool) Name() string

func (*MCPTool) Parameters

func (t *MCPTool) Parameters() ToolParameters

func (*MCPTool) String

func (t *MCPTool) String() string

type MultimodalToolResult

type MultimodalToolResult struct {
	Text   string
	Images []*schema.ContentBlock
}

MultimodalToolResult is a tool result that contains both text and image parts.

func (*MultimodalToolResult) ImageParts

func (m *MultimodalToolResult) ImageParts() []*schema.ContentBlock

func (*MultimodalToolResult) String

func (m *MultimodalToolResult) String() string

type Step

type Step struct {
	Thought            string                 `json:"thought"`
	Action             string                 `json:"action"`
	UseToolOrNot       bool                   `json:"use_tool_or_not"`
	ToolName           string                 `json:"tool_name"`
	ActionInputParam   map[string]any         `json:"action_input_param"`
	IsFinalAnswer      bool                   `json:"is_final_answer"`
	Observation        string                 `json:"observation"`
	ObservationImages  []*schema.ContentBlock `json:"-"`
	OptimizationAdvice *string                `json:"optimization_advice,omitempty"`
	IsCompressed       bool                   `json:"-"`
	// Usage is the total token usage associated with this step.
	Usage         *AgentUsage `json:"usage,omitempty"`
	ModelUsage    *AgentUsage `json:"model_usage,omitempty"`
	CallbackUsage *AgentUsage `json:"callback_usage,omitempty"`
}

The optimization advice will affect the agent's next step's behavior

func NewStepFromString

func NewStepFromString(s string) (*Step, error)

func (*Step) AddCallbackUsage

func (s *Step) AddCallbackUsage(promptTokens, cachedTokens, completionTokens int)

func (*Step) AddModelUsage

func (s *Step) AddModelUsage(promptTokens, cachedTokens, completionTokens int)

func (*Step) AddUsage

func (s *Step) AddUsage(promptTokens, cachedTokens, completionTokens int)

func (*Step) ToPrompt

func (s *Step) ToPrompt() (*schema.AgenticMessage, error)

func (*Step) ToString

func (s *Step) ToString() (string, error)

type ThinkArgs

type ThinkArgs struct {
	Interim               string
	UserInput             AgentUserInput
	Steps                 []*Step
	SpecialRequirements   []string
	Compress              bool
	SkillUsageInstruction string
	EnablePlanning        bool
}

type ThinkResult

type ThinkResult struct {
	NewStep                 *Step
	IsCompressed            bool
	Interim                 string
	CompressedPreviousSteps []*Step
	PromptTokens            int
	CompletionTokens        int
}

type Tool

type Tool interface {
	Name() string
	Description() string
	// Must be constructed by NewToolParameters
	Parameters() ToolParameters
	String() string
	Execute(*AgentContext, map[string]any) ToolResult
}

func InterruptLoopAfter

func InterruptLoopAfter(tool Tool) Tool

InterruptLoopAfter wraps a normal tool so executing it requests the agent loop to stop after the current tool batch is committed.

func ListMCPTools

func ListMCPTools(ctx context.Context, cli client.MCPClient) ([]Tool, error)

ListMCPTools fetches all tools exposed by an MCP server and wraps them as agent tools.

func WrapToolName

func WrapToolName(t Tool, name string) Tool

WrapToolName returns a tool wrapper with an overridden Name() if needed.

type ToolExecutionOptions

type ToolExecutionOptions struct {
	EnableParallel bool
	MaxConcurrency int
}

type ToolParameters

type ToolParameters map[string]any

type ToolProperty

type ToolProperty struct {
	Name        string         `json:"name"`
	Type        string         `json:"type"` // JSON Schema type: string, integer, number, boolean, array, object
	Required    bool           `json:"required"`
	Description string         `json:"description,omitempty"`
	Items       *ToolProperty  `json:"items,omitempty"`      // for array
	Properties  []ToolProperty `json:"properties,omitempty"` // for object
}

ToolProperty represents a single property in a tool's parameters schema.

type ToolResult

type ToolResult interface {
	String() string
	// ImageParts returns image content parts from the tool result.
	// Returns nil if the result contains no images.
	ImageParts() []*schema.ContentBlock
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL