Documentation
¶
Index ¶
- Variables
- func MergeActions(base, extra map[string]any) map[string]any
- func NewAgentContext(ctx context.Context, agent Agent) context.Context
- func NewAgentTool(agent Agent) tools.Tool
- func NewInvocationID() string
- func NewMessageID() string
- func NewSessionContext(ctx context.Context, session Session) context.Context
- type Agent
- type AgentContext
- type AgentOption
- func WithContext(enabled bool) AgentOption
- func WithDescription(description string) AgentOption
- func WithInputSchema(schema *jsonschema.Schema) AgentOption
- func WithInstruction(instruction string) AgentOption
- func WithInstructionProvider(p InstructionProvider) AgentOption
- func WithMaxIterations(n int) AgentOption
- func WithMiddleware(ms ...Middleware) AgentOption
- func WithModel(model ModelProvider) AgentOption
- func WithOutputKey(key string) AgentOption
- func WithOutputSchema(schema *jsonschema.Schema) AgentOption
- func WithSkills(skillList ...skills.Skill) AgentOption
- func WithTools(tools ...tools.Tool) AgentOption
- func WithToolsResolver(r tools.Resolver) AgentOption
- type ContextCompressor
- type DataPart
- type FilePart
- type Generator
- type HandleFunc
- type Handler
- type InstructionProvider
- type Invocation
- type MIMEType
- type Message
- func (m *Message) Clone() *Message
- func (m *Message) Data() *DataPart
- func (m *Message) File() *FilePart
- func (m *Message) MarshalJSON() ([]byte, error)
- func (m *Message) Reasoning() string
- func (m *Message) String() string
- func (m *Message) Text() string
- func (m *Message) UnmarshalJSON(data []byte) error
- type Middleware
- type ModelProvider
- type ModelRequest
- type ModelResponse
- type Part
- type ReasoningPart
- type Role
- type RunOption
- type RunOptions
- type Runner
- type RunnerOption
- type Session
- type SessionOption
- type State
- type Status
- type TextPart
- type TokenCounter
- type TokenUsage
- type ToolContext
- type ToolPart
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNoSessionContext is returned when a session context is missing from the context. ErrNoSessionContext = errors.New("session not found in context") // ErrNoAgentContext is returned when an agent context is missing from the context. ErrNoAgentContext = errors.New("agent not found in context") // ErrMissingInvocationContext is returned when an invocation context is missing from the context. ErrNoInvocationContext = errors.New("invocation not found in context") // ErrModelProviderRequired is returned when a model provider is not supplied where required. ErrModelProviderRequired = errors.New("model provider is required") // ErrMaxIterationsExceeded is returned when an agent exceeds the maximum allowed iterations. ErrMaxIterationsExceeded = errors.New("maximum iterations exceeded in agent execution") // ErrMissingFinalResponse is returned when an agent's stream ends without a final response. ErrNoFinalResponse = errors.New("stream ended without a final response") // ErrInterrupted is returned when execution is interrupted. ErrInterrupted = errors.New("execution was interrupted") // ErrLoopEscalated is returned when a loop condition signals escalation to an outer handler. ErrLoopEscalated = errors.New("loop escalated to outer handler") )
var (
// Version is the current blades version.
Version = buildVersion("github.com/CycleZero/blades")
)
Functions ¶
func MergeActions ¶
MergeActions merges two action maps, with values from extra overriding those in base.
func NewAgentContext ¶
NewAgentContext returns a new context with the given AgentContext.
func NewAgentTool ¶
NewAgentTool creates a new tool that wraps the given Agent.
func NewInvocationID ¶
func NewInvocationID() string
NewInvocationID generates a new unique invocation ID.
func NewMessageID ¶
func NewMessageID() string
NewMessageID generates a new random message identifier.
Types ¶
type Agent ¶
type Agent interface {
// Name returns the name of the agent.
Name() string
// Description returns a brief description of the agent's functionality.
Description() string
// Run processes the given invocation and returns a generator that yields messages or errors.
Run(context.Context, *Invocation) Generator[*Message, error]
}
Agent represents an autonomous agent that can process invocations and produce a sequence of messages.
type AgentContext ¶
AgentContext provides metadata about an agent.
func FromAgentContext ¶
func FromAgentContext(ctx context.Context) (AgentContext, bool)
FromAgentContext retrieves the AgentContext from the context, if present.
type AgentOption ¶
type AgentOption func(*agent)
AgentOption is an option for configuring the Agent.
func WithContext ¶
func WithContext(enabled bool) AgentOption
WithContext controls whether the Agent loads the full session history into each model call. When enabled (true), session.History is called before every model request so the model has the complete conversation context. By default (when WithContext is not used or enabled is false), only the messages produced within the current invocation are sent to the model, making the agent stateless with respect to prior turns.
func WithDescription ¶
func WithDescription(description string) AgentOption
WithDescription sets the description for the Agent.
func WithInputSchema ¶
func WithInputSchema(schema *jsonschema.Schema) AgentOption
WithInputSchema sets the input schema for the Agent.
func WithInstruction ¶
func WithInstruction(instruction string) AgentOption
WithInstruction sets the instruction for the Agent.
func WithInstructionProvider ¶
func WithInstructionProvider(p InstructionProvider) AgentOption
WithInstructionProvider sets a dynamic instruction provider for the Agent.
func WithMaxIterations ¶
func WithMaxIterations(n int) AgentOption
WithMaxIterations sets the maximum number of iterations for the Agent. By default, it is set to 10.
func WithMiddleware ¶
func WithMiddleware(ms ...Middleware) AgentOption
WithMiddleware sets the middleware for the Agent.
func WithModel ¶
func WithModel(model ModelProvider) AgentOption
WithModel sets the model provider for the Agent.
func WithOutputKey ¶
func WithOutputKey(key string) AgentOption
WithOutputKey sets the output key for storing the Agent's output in the session state.
func WithOutputSchema ¶
func WithOutputSchema(schema *jsonschema.Schema) AgentOption
WithOutputSchema sets the output schema for the Agent.
func WithSkills ¶
func WithSkills(skillList ...skills.Skill) AgentOption
WithSkills sets skills for the Agent.
func WithTools ¶
func WithTools(tools ...tools.Tool) AgentOption
WithTools sets the tools for the Agent.
func WithToolsResolver ¶
func WithToolsResolver(r tools.Resolver) AgentOption
WithToolsResolver sets a tools resolver for the Agent. The resolver can dynamically provide tools from various sources (e.g., MCP servers, plugins). Tools are resolved lazily on first use.
type ContextCompressor ¶
type ContextCompressor interface {
// Compress filters, truncates, or compresses messages to fit within the
// context window. System/instruction content is handled separately via
// ModelRequest.Instruction and is never passed to Compress.
Compress(ctx context.Context, messages []*Message) ([]*Message, error)
}
ContextCompressor compresses, truncates, or filters the message list before each model call to keep it within the context window budget.
type DataPart ¶
type DataPart struct {
Name string `json:"name"`
Bytes []byte `json:"bytes"`
MIMEType MIMEType `json:"mimeType"`
}
DataPart is a file represented by its byte content.
type FilePart ¶
type FilePart struct {
Name string `json:"name"`
URI string `json:"uri"`
MIMEType MIMEType `json:"mimeType"`
}
FilePart is a reference to a file by its URI.
type Generator ¶
Generator is a generic type representing a sequence generator that yields values of type T or errors of type E.
type HandleFunc ¶
HandleFunc is an adapter to allow the use of ordinary functions as Handlers.
func (HandleFunc) Handle ¶
func (f HandleFunc) Handle(ctx context.Context, invocation *Invocation) Generator[*Message, error]
Handle implements the Handler interface for HandleFunc.
type Handler ¶
Handler defines a function that processes an Invocation and returns a Generator of Messages.
type InstructionProvider ¶
InstructionProvider is a function type that generates instructions based on the given context.
type Invocation ¶
type Invocation struct {
ID string
Model string
Resume bool
Stream bool
Session Session
Instruction *Message
Message *Message
// EphemeralMessages are appended to the next model request only.
// They are not persisted into the session history.
EphemeralMessages []*Message
Tools []tools.Tool
// contains filtered or unexported fields
}
Invocation holds information about the current invocation.
func (*Invocation) Clone ¶
func (inv *Invocation) Clone() *Invocation
Clone creates a deep copy of the Invocation. All clones share the same committed *atomic.Bool pointer. The first agent (original or any clone) to call CompareAndSwap(false, true) on it will perform the session append; all others skip. This is safe for concurrent use.
type MIMEType ¶
type MIMEType string
MIMEType represents the media type of content.
const ( // Text and markdown mime types. MIMEText MIMEType = "text/plain" MIMEMarkdown MIMEType = "text/markdown" // Common image mime types. MIMEImagePNG MIMEType = "image/png" MIMEImageJPEG MIMEType = "image/jpeg" MIMEImageWEBP MIMEType = "image/webp" // Common audio mime types (non-exhaustive). MIMEAudioWAV MIMEType = "audio/wav" MIMEAudioMP3 MIMEType = "audio/mpeg" MIMEAudioOGG MIMEType = "audio/ogg" MIMEAudioAAC MIMEType = "audio/aac" MIMEAudioFLAC MIMEType = "audio/flac" MIMEAudioOpus MIMEType = "audio/opus" MIMEAudioPCM MIMEType = "audio/pcm" // Common video mime types (non-exhaustive). MIMEVideoMP4 MIMEType = "video/mp4" MIMEVideoOGG MIMEType = "video/ogg" )
type Message ¶
type Message struct {
ID string `json:"id"`
Role Role `json:"role"`
Parts []Part `json:"parts"`
Author string `json:"author"`
InvocationID string `json:"invocationId,omitempty"`
Status Status `json:"status"`
FinishReason string `json:"finishReason,omitempty"`
TokenUsage TokenUsage `json:"tokenUsage,omitempty"`
Actions map[string]any `json:"actions,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
Message represents a single message in a conversation.
func AppendMessages ¶
AppendMessages appends extra messages to base, replacing any messages in base that have matching IDs in extra.
func AssistantMessage ¶
AssistantMessage creates an assistant-authored message from parts.
func MergeParts ¶
MergeParts merges the Parts of two messages, mutating and returning base. If base is nil, extra is returned. If extra is nil, base is returned.
func NewAssistantMessage ¶
NewAssistantMessage creates a new assistant message with the given status.
func SystemMessage ¶
SystemMessage creates a system-authored message from parts.
func UserMessage ¶
UserMessage creates a user-authored message from parts.
func (*Message) MarshalJSON ¶
MarshalJSON encodes the message, tagging each part with its concrete type so the parts can be restored by UnmarshalJSON.
func (*Message) Reasoning ¶
Reasoning returns the concatenated reasoning / chain-of-thought content of the message, or an empty string if the model produced none.
func (*Message) Text ¶
Text returns the first text part of the message, or an empty string if none exists.
func (*Message) UnmarshalJSON ¶
UnmarshalJSON decodes a message previously produced by MarshalJSON, restoring each Part from its type tag.
type Middleware ¶
Middleware wraps a Handler and returns a new Handler with additional behavior. It is applied in a chain (outermost first) using ChainMiddlewares.
func ChainMiddlewares ¶
func ChainMiddlewares(mws ...Middleware) Middleware
ChainMiddlewares composes middlewares into one, applying them in order. The first middleware becomes the outermost wrapper.
type ModelProvider ¶
type ModelProvider interface {
// Name returns the model name.
Name() string
// Generate executes the request and returns a single assistant response.
Generate(context.Context, *ModelRequest) (*ModelResponse, error)
// NewStreaming executes the request and returns a stream of assistant responses.
NewStreaming(context.Context, *ModelRequest) Generator[*ModelResponse, error]
}
ModelProvider is an interface for multimodal chat-style models.
type ModelRequest ¶
type ModelRequest struct {
Tools []tools.Tool `json:"tools,omitempty"`
Messages []*Message `json:"messages"`
Instruction *Message `json:"instruction,omitempty"`
InputSchema *jsonschema.Schema `json:"inputSchema,omitempty"`
OutputSchema *jsonschema.Schema `json:"outputSchema,omitempty"`
}
ModelRequest is a multimodal chat-style request to the provider.
type ModelResponse ¶
type ModelResponse struct {
Message *Message `json:"message"`
}
ModelResponse is a single assistant message as a result of generation.
type Part ¶
type Part interface {
// contains filtered or unexported methods
}
Part is a part of a message, which can be text or a file.
func NewMessageParts ¶
NewMessageParts converts a heterogeneous list of content inputs into model parts. Accepts raw string, Text, FileURI, and FileBytes.
type ReasoningPart ¶
type ReasoningPart struct {
Text string `json:"text"`
}
ReasoningPart is the model's reasoning / chain-of-thought content. It is surfaced to callers for observability but is deliberately excluded from Message.Text(), so it never becomes part of the answer and is never echoed back to the model on subsequent turns.
type RunOption ¶
type RunOption func(*RunOptions)
RunOption defines options for configuring the Runner.
func WithInvocationID ¶
WithInvocationID sets a custom invocation ID for the Runner.
func WithResume ¶
WithResume indicates whether to resume from the last session state.
func WithSession ¶
WithSession sets a custom session for the Runner.
type RunOptions ¶
RunOptions holds configuration options for running the agent.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner is responsible for executing a Runnable agent within a session context.
func NewRunner ¶
func NewRunner(rootAgent Agent, opts ...RunnerOption) *Runner
NewRunner creates a new Runner with the given agent and options.
type RunnerOption ¶
type RunnerOption func(*Runner)
RunnerOption configures a Runner at construction time.
type Session ¶
type Session interface {
ID() string
State() State
SetState(string, any)
Append(context.Context, *Message) error
// History returns the message history prepared for the next model call.
// When a ContextCompressor is configured, the history is compressed before
// being returned; otherwise the raw message list is returned unchanged.
History(ctx context.Context) ([]*Message, error)
}
Session holds the state of a flow along with a unique session ID.
func EnsureSession ¶
EnsureSession returns the Session stored in ctx, or a new in-memory Session if none is present.
func NewSession ¶
func NewSession(opts ...SessionOption) Session
NewSession creates a new Session instance with an auto-generated UUID. Pass SessionOption values to configure the session (e.g. WithContextCompressor). Legacy map arguments are still accepted for backwards compatibility.
type SessionOption ¶
type SessionOption func(*sessionInMemory)
SessionOption configures a Session at construction time.
func WithContextCompressor ¶
func WithContextCompressor(c ContextCompressor) SessionOption
WithContextCompressor sets the ContextCompressor used by Session.History to compress the message history before returning it for each model call.
type Status ¶
type Status string
Status indicates the state of a message.
const ( // StatusInProgress indicates the message is being generated. StatusInProgress Status = "in_progress" // StatusIncomplete indicates the message is partially generated. StatusIncomplete Status = "incomplete" // StatusCompleted indicates the message is fully generated. StatusCompleted Status = "completed" )
type TokenCounter ¶
TokenCounter estimates the number of tokens for a set of messages. Implementations may use model-specific tokenizers for precise counting, or rely on heuristic approximations.
type TokenUsage ¶
type TokenUsage struct {
InputTokens int64 `json:"inputTokens"`
OutputTokens int64 `json:"outputTokens"`
TotalTokens int64 `json:"totalTokens"`
}
TokenUsage tracks token consumption for a message.
type ToolContext ¶
type ToolContext = tools.ToolContext
ToolContext is an alias for tools.ToolContext so that existing callers of blades.ToolContext / blades.FromToolContext continue to work unchanged.
type ToolPart ¶
type ToolPart struct {
ID string `json:"id"`
Name string `json:"name"`
Request string `json:"arguments"`
Response string `json:"result,omitempty"`
Completed bool `json:"completed,omitempty"`
}
ToolPart is a tool call, containing its request, response, and completion state.
func NewToolPart ¶
NewToolPart creates a tool call part that has not completed yet.

