react

package module
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 10 Imported by: 0

README

react - Simple yet powerful agent framework for Go

  • A ReAct agent is a class of AI agent that is capable of advanced tasks through tool calling.
  • This package implements a version of a ReAct agent in Go, with a few extra features.

Features

  • Backed by the power of jpf: The LLM handling is extremely robust and model-agnostic.
  • Easy to create custom tools: To create a tool, you just need to implement a simple interface.
  • Built-in dynamic skill retrieval: Named PromptFragment in this package, you can add skills to the agent and they will be intelligently injected into its context when relevant.
  • Supports Streaming: You can inject callbacks for both streaming back the text of the final response, and streaming back messages as they are created.
  • Clean message abstraction: The agent history is stored as a typed list of messages, differentiated by use. These only get converted into the API messages right before sending to the LLM.

Usage

  • Create an agent and ask it a question:
agent := NewCraig(
    modelBuilder,
    WithCraigTools(tool1, tool2),
    WithCraigPersonality("You are an ai assistant"),
    WithCraigFragments(PromptFragment{
        Key: "time_tool",
        When: "The user asks the agent for the time or date",
        Content: "When asked for the time, the agent will respond in HH:MM 24hr format. When asked the date, DD/MM/YYYY.",
    }),
)

response, err := agent.Send("Whats the time")
  • Stream the response back to the terminal
type printStreamer struct{}
func (*printStreamer) TrySendTextChunk(chunk string) {fmt.Print(chunk)}

response, err := agent.Send("Write 3 haikus", WithResponseStreamer(&printStreamer{}))
// The response will be printed to the terminal as the API streams it back
  • Agents use model builders, which are the method of providing the agent with the llm to use
type ModelBuilder interface {
	AgentModelBuilder
	FragmentSelectorModelBuilder
}

type AgentModelBuilder interface {
	// Build a model for the agent.
	// A struct may be passed as the response type for a json schema, or it may be nil.
	// The stream callbacks may also be nil.
	BuildAgentModel(responseType any, onInitFinalStream func(), onDataFinalStream func(string)) jpf.Model
}

type FragmentSelectorModelBuilder interface {
	// Build a model for a fragment selector.
	// A struct may be passed as the response type for a json schema, or it may be nil.
	BuildFragmentSelectorModel(responseType any) jpf.Model
}

Documentation

Index

Constants

View Source
const (
	ModeCollectContext = iota
	ModeReasonAct
	ModeAnswerUser
)

Variables

This section is empty.

Functions

func WithPersonality added in v0.0.6

func WithPersonality(personality string) func(kw *newKwargs)

func WithSkills added in v0.0.6

func WithSkills(skills ...Skill) func(kw *newKwargs)

func WithTools added in v0.0.6

func WithTools(tools ...Tool) func(kw *newKwargs)

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

func New added in v0.0.6

func New(mb ModelBuilder, opts ...NewOpt) *Agent

func NewFromSaved added in v0.0.6

func NewFromSaved(mb ModelBuilder, messages []Message, opts ...NewOpt) *Agent

func (*Agent) Messages

func (ag *Agent) Messages() iter.Seq[Message]

func (*Agent) Send

func (ag *Agent) Send(msg string, opts ...SendMessageOpt) (string, error)

type AgentMode

type AgentMode uint8

type AgentModelBuilder

type AgentModelBuilder interface {
	// Build a model for the agent.
	// A struct may be passed as the response type for a json schema, or it may be nil.
	// The stream callbacks may also be nil.
	BuildAgentModel(responseType any, onInitFinalStream func(), onDataFinalStream func(string)) jpf.Model
}

type AvailableToolDefinition

type AvailableToolDefinition struct {
	Name        string
	Description []string
}

type FragmentSelectorModelBuilder

type FragmentSelectorModelBuilder interface {
	// Build a model for a fragment selector.
	// A struct may be passed as the response type for a json schema, or it may be nil.
	BuildFragmentSelectorModel(responseType any) jpf.Model
}

type InsertedSkill added in v0.0.6

type InsertedSkill struct {
	Skill
	NowRemainFor int
}

type Message

type Message interface {
	// contains filtered or unexported methods
}

Message is a sum type defining the structured data that can live in agent history.

func DeserialiseMessages added in v0.0.8

func DeserialiseMessages(smsgs []SerialisedMessage) []Message

type MessageStreamer

type MessageStreamer interface {
	// Try to send a message, ignoring errors.
	TrySendMessage(msg Message)
}

MessageStreamer defines a callback interface that can be used to listen to new messages that the agent creates.

type ModelBuilder

type ModelBuilder interface {
	AgentModelBuilder
	FragmentSelectorModelBuilder
}

type NewOpt added in v0.0.6

type NewOpt func(*newKwargs)

type Notification added in v0.0.8

type Notification struct {
	Kind    string
	Content string
}

type SendMessageOpt

type SendMessageOpt func(*sendMessageKwargs)

func WithMessageStreamer

func WithMessageStreamer(streamer MessageStreamer) SendMessageOpt

In addition to other message streamers, use the provided streamer.

func WithNotifications

func WithNotifications(notifications ...Notification) SendMessageOpt

func WithResponseStreamer

func WithResponseStreamer(streamer TextStreamer) SendMessageOpt

In addition to other response streamers, use the provided streamer.

type SerialisedMessage added in v0.0.8

type SerialisedMessage struct {
	Kind             SerialisedMessageKind     `json:"kind"`
	Content          string                    `json:"content,omitempty"`
	Reasoning        string                    `json:"reasoning,omitempty"`
	NotificationKind string                    `json:"notification_kind,omitempty"`
	ToolCalls        []ToolCall                `json:"tool_calls,omitempty"`
	Responses        []ToolResponse            `json:"responses,omitempty"`
	Skills           []InsertedSkill           `json:"skills,omitempty"`
	AvailableTools   []AvailableToolDefinition `json:"available_tools,omitempty"`
	Mode             AgentMode                 `json:"mode,omitempty"`
	Personality      string                    `json:"personality,omitempty"`
}

func SerialiseMessages added in v0.0.8

func SerialiseMessages(msgs []Message) []SerialisedMessage

type SerialisedMessageKind added in v0.0.8

type SerialisedMessageKind string
const (
	KindSystem         SerialisedMessageKind = "system"
	KindUser           SerialisedMessageKind = "user"
	KindAgent          SerialisedMessageKind = "agent"
	KindToolCalls      SerialisedMessageKind = "tool_calls"
	KindToolResponse   SerialisedMessageKind = "tool_response"
	KindNotification   SerialisedMessageKind = "notification"
	KindSkills         SerialisedMessageKind = "skills"
	KindAvailableTools SerialisedMessageKind = "available_tools"
	KindModeSwitch     SerialisedMessageKind = "mode_switch"
	KindPersonality    SerialisedMessageKind = "personality"
)

type Skill added in v0.0.4

type Skill struct {
	// A sensible snake_case key
	Key string
	// When should this be applied? If empty will always be applied.
	When string
	// The content that is not seen by the selector but is seen by the agent when chosen.
	Content string
	// How many turns after the turn it is inserted will the skill remain in context
	RemainFor int
}

func (Skill) IsConditional added in v0.0.4

func (f Skill) IsConditional() bool

type SkillSelector added in v0.0.4

type SkillSelector interface {
	// Select any relevant [Skill]s that should be added to the conversation.
	SelectSkills([]Skill, []Message) ([]Skill, error)
}

SkillSelector defines an object that can choose relevant [Skill]s to a conversation.

func NewSkillSelector added in v0.0.4

func NewSkillSelector(modelBuilder FragmentSelectorModelBuilder) SkillSelector

type TextStreamer

type TextStreamer interface {
	// Try to send a response text chunk back, ignoring errors.
	TrySendTextChunk(chunk string)
}

TextStreamer defines a callback interface that can be used to listen to text being streamed back from the final agent response.

type Tool

type Tool interface {
	// The name of the tool to be used by the agent. Should probably be snake_case.
	Name() string
	// Describe the tool in short bullet points to the agent.
	// Includes which parameters to provide.
	// Parameters can be described as any json type.
	Description() []string
	// Call the tool, providing a formatted response or an error if the tool call failed.
	// The values of the args will be the direct result of json decoding the tool call args.
	Call(map[string]any) (string, error)
}

Tool is a runnable object that can be both described to and called by an agent.

type ToolCall

type ToolCall struct {
	ToolName string
	ToolArgs []ToolCallArg
}

type ToolCallArg

type ToolCallArg struct {
	ArgName  string
	ArgValue any
}

type ToolResponse

type ToolResponse struct {
	Response string
}

Jump to

Keyboard shortcuts

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