swarm

package module
v0.0.0-...-042073b Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FunctionToDefinition

func FunctionToDefinition(af AgentFunction) llm.Function

FunctionToDefinition converts an AgentFunction to a llm.Function

func ProcessAndPrintResponse

func ProcessAndPrintResponse(response Response)

ProcessAndPrintResponse processes and prints the response from the LLM. It uses different colors for different roles: blue for "assistant" and magenta for "function" or "tool".

func RunDemoLoop

func RunDemoLoop(client *Swarm, agent *Agent)

Types

type Agent

type Agent struct {
	Name              string                                               // The name of the agent.
	Model             string                                               // The model identifier.
	Provider          llm.LLMProvider                                      // The LLM provider to use.
	Config            *ClientConfig                                        // Provider-specific configuration.
	Instructions      string                                               // Static instructions for the agent.
	InstructionsFunc  func(contextVariables map[string]interface{}) string // Function to generate dynamic instructions based on context.
	Functions         []AgentFunction                                      // A list of functions the agent can perform.
	Memory            *MemoryStore                                         // Memory store for the agent.
	ParallelToolCalls bool                                                 // Whether to allow parallel tool calls.
}

Agent represents an entity with specific attributes and behaviors.

func NewAgent

func NewAgent(name, model string, provider llm.LLMProvider) *Agent

NewAgent creates a new agent with initialized memory store

func (*Agent) WithConfig

func (a *Agent) WithConfig(config *ClientConfig) *Agent

WithConfig sets the configuration for the agent

func (*Agent) WithFunctions

func (a *Agent) WithFunctions(functions []AgentFunction) *Agent

WithFunctions sets the functions available to the agent

func (*Agent) WithInstructions

func (a *Agent) WithInstructions(instructions string) *Agent

WithInstructions sets the static instructions for the agent

func (*Agent) WithInstructionsFunc

func (a *Agent) WithInstructionsFunc(f func(map[string]interface{}) string) *Agent

WithInstructionsFunc sets the dynamic instructions function for the agent

func (*Agent) WithParallelToolCalls

func (a *Agent) WithParallelToolCalls(enabled bool) *Agent

WithParallelToolCalls enables or disables parallel tool calls

type AgentConfig

type AgentConfig struct {
	Agent            *Agent
	Messages         []llm.Message
	ContextVariables map[string]interface{}
	ModelOverride    string
	Stream           bool
	Debug            bool
	MaxTurns         int
	ExecuteTools     bool
}

AgentConfig holds the configuration for a single agent execution

type AgentFunction

type AgentFunction struct {
	Name        string                                                                            // The name of the function.
	Description string                                                                            // Description of what the function does.
	Parameters  map[string]interface{}                                                            // Parameters for the function.
	Function    func(args map[string]interface{}, contextVariables map[string]interface{}) Result // The actual function implementation.
}

AgentFunction represents a function that can be performed by an agent

type ClientConfig

type ClientConfig struct {
	Provider           llm.LLMProvider
	AuthToken          string
	BaseURL            string
	OrgID              string
	APIVersion         string
	AssistantVersion   string
	ModelMapperFunc    func(model string) string // replace model to provider-specific deployment name
	HTTPClient         *http.Client
	EmptyMessagesLimit uint
	Options            map[string]interface{} // Additional provider-specific options
}

ClientConfig represents the configuration for an LLM client

type ConcurrentResult

type ConcurrentResult struct {
	AgentName string
	Response  Response
	Error     error
}

ConcurrentResult represents the result from a single agent's execution

type ConcurrentSwarm

type ConcurrentSwarm struct {
	*Swarm
}

ConcurrentSwarm manages concurrent execution of multiple agents

func NewConcurrentSwarm

func NewConcurrentSwarm(apiKey string, provider llm.LLMProvider) *ConcurrentSwarm

NewConcurrentSwarm creates a new ConcurrentSwarm instance

func (*ConcurrentSwarm) RunConcurrent

func (cs *ConcurrentSwarm) RunConcurrent(ctx context.Context, configs map[string]AgentConfig) []ConcurrentResult

RunConcurrent executes multiple agents concurrently and returns their results

func (*ConcurrentSwarm) RunConcurrentOrdered

func (cs *ConcurrentSwarm) RunConcurrentOrdered(ctx context.Context, orderedConfigs []struct {
	Name   string
	Config AgentConfig
}) []ConcurrentResult

RunConcurrentOrdered executes multiple agents concurrently and returns their results in the order specified

type CycleHandling

type CycleHandling int

CycleHandling represents how to handle detected cycles

const (
	StopOnCycle CycleHandling = iota
	ContinueOnCycle
)

type DefaultStreamHandler

type DefaultStreamHandler struct{}

DefaultStreamHandler provides a basic implementation of StreamHandler

func (*DefaultStreamHandler) OnComplete

func (h *DefaultStreamHandler) OnComplete(message llm.Message)

func (*DefaultStreamHandler) OnError

func (h *DefaultStreamHandler) OnError(err error)

func (*DefaultStreamHandler) OnStart

func (h *DefaultStreamHandler) OnStart()

func (*DefaultStreamHandler) OnToken

func (h *DefaultStreamHandler) OnToken(token string)

func (*DefaultStreamHandler) OnToolCall

func (h *DefaultStreamHandler) OnToolCall(toolCall llm.ToolCall)

type Memory

type Memory struct {
	Content    string                 `json:"content"`    // The actual memory content
	Type       string                 `json:"type"`       // Type of memory (e.g., "conversation", "fact", "task")
	Context    map[string]interface{} `json:"context"`    // Associated context
	Timestamp  time.Time              `json:"timestamp"`  // When the memory was created
	Importance float64                `json:"importance"` // Importance score (0-1)
	References []string               `json:"references"` // References to related memories
}

Memory represents a single memory entry

type MemoryStore

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

MemoryStore manages agent memories

func NewMemoryStore

func NewMemoryStore(maxShortTerm int) *MemoryStore

NewMemoryStore creates a new memory store with default settings

func (*MemoryStore) AddMemory

func (ms *MemoryStore) AddMemory(memory Memory)

AddMemory adds a new memory to both short and long-term storage

func (*MemoryStore) GetRecentMemories

func (ms *MemoryStore) GetRecentMemories(n int) []Memory

GetRecentMemories retrieves the n most recent memories

func (*MemoryStore) LoadMemories

func (ms *MemoryStore) LoadMemories(data []byte) error

LoadMemories loads memories from JSON data

func (*MemoryStore) SearchMemories

func (ms *MemoryStore) SearchMemories(memoryType string, context map[string]interface{}) []Memory

SearchMemories searches for memories based on type and context

func (*MemoryStore) SerializeMemories

func (ms *MemoryStore) SerializeMemories() ([]byte, error)

SerializeMemories serializes all memories to JSON

type Response

type Response struct {
	Messages         []llm.Message
	Agent            *Agent
	ContextVariables map[string]interface{}
}

Response represents the response from an agent

type Result

type Result struct {
	Success bool        // Whether the function execution was successful
	Data    interface{} // Any data returned by the function
	Error   error       // Any error that occurred during execution
	Agent   *Agent      // Active agent
}

Result represents the result of a function execution

type StepResult

type StepResult struct {
	AgentName  string
	Input      []llm.Message
	Output     []llm.Message
	Error      error
	StartTime  time.Time
	EndTime    time.Time
	NextAgent  string
	StepNumber int
}

StepResult represents the outcome of a single workflow step

type StreamHandler

type StreamHandler interface {
	OnStart()
	OnToken(token string)
	OnToolCall(toolCall llm.ToolCall)
	OnComplete(message llm.Message)
	OnError(err error)
}

StreamHandler represents a handler for streaming responses

type Swarm

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

Swarm represents the main structure

func NewSwarm

func NewSwarm(apiKey string, provider llm.LLMProvider) *Swarm

NewSwarm initializes a new Swarm instance with an LLM client

func (*Swarm) Run

func (s *Swarm) Run(
	ctx context.Context,
	agent *Agent,
	messages []llm.Message,
	contextVariables map[string]interface{},
	modelOverride string,
	stream bool,
	debug bool,
	maxTurns int,
	executeTools bool,
) (Response, error)

Run executes the chat interaction loop with the agent

func (*Swarm) StreamingResponse

func (s *Swarm) StreamingResponse(
	ctx context.Context,
	agent *Agent,
	messages []llm.Message,
	contextVariables map[string]interface{},
	modelOverride string,
	handler StreamHandler,
	debug bool,
) error

StreamingResponse handles streaming chat completions

type TeamType

type TeamType string

TeamType represents a type of agent team

const (
	ResearchTeam   TeamType = "research"
	DocumentTeam   TeamType = "document"
	SupervisorTeam TeamType = "supervisor"
	AnalysisTeam   TeamType = "analysis"
	DeveloperTeam  TeamType = "developer"
)

type VisualizationHook

type VisualizationHook interface {
	OnWorkflowStart(workflow *Workflow)
	OnAgentStart(agentName string, step int)
	OnAgentComplete(agentName string, step int, duration time.Duration)
	OnMessageSent(fromAgent, toAgent, content string)
	OnCycleDetected(fromAgent, toAgent string, count int)
	OnWorkflowEnd(workflow *Workflow)
}

VisualizationHook defines the interface for workflow visualization

type Workflow

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

Workflow represents a collection of agents and their connections.

func NewWorkflow

func NewWorkflow(apikey string, provider llm.LLMProvider, workflowType WorkflowType) *Workflow

NewWorkflow initializes a new Workflow instance.

func (*Workflow) AddAgent

func (wf *Workflow) AddAgent(agent *Agent)

AddAgent adds an agent to the workflow.

func (*Workflow) AddAgentToTeam

func (wf *Workflow) AddAgentToTeam(agent *Agent, team TeamType)

AddAgentToTeam adds an agent to a specific team

func (*Workflow) ConnectAgents

func (wf *Workflow) ConnectAgents(fromAgent, toAgent string) error

ConnectAgents creates a connection between two agents.

func (*Workflow) Execute

func (wf *Workflow) Execute(startAgent string, userRequest string) (*WorkflowResult, error)

Execute runs a workflow and returns detailed results including step outcomes

func (*Workflow) GetAgents

func (wf *Workflow) GetAgents() map[string]*Agent

GetAgents returns all agents in the workflow

func (*Workflow) GetAllStepResults

func (wf *Workflow) GetAllStepResults() []StepResult

GetAllStepResults returns all step results

func (*Workflow) GetConnections

func (wf *Workflow) GetConnections() map[string][]string

GetConnections returns all connections in the workflow

func (*Workflow) GetCurrentAgent

func (wf *Workflow) GetCurrentAgent() string

GetCurrentAgent returns the currently active agent

func (*Workflow) GetInstruction

func (wf *Workflow) GetInstruction(key string) WorkflowInstruction

GetInstruction returns the instruction at the given key

func (*Workflow) GetLastStepResult

func (wf *Workflow) GetLastStepResult() (*StepResult, error)

GetLastStepResult returns the result of the last executed step

func (*Workflow) GetRoutingLog

func (wf *Workflow) GetRoutingLog() []string

GetRoutingLog returns the routing history

func (*Workflow) GetStepResult

func (wf *Workflow) GetStepResult(stepNumber int) (*StepResult, error)

GetStepResult returns the result of a specific step

func (*Workflow) GetTeamLeaders

func (wf *Workflow) GetTeamLeaders() map[TeamType]string

GetTeamLeaders returns all team leaders in the workflow

func (*Workflow) GetTeams

func (wf *Workflow) GetTeams() map[TeamType][]*Agent

GetTeams returns all teams in the workflow

func (*Workflow) Run

func (wf *Workflow) Run(key string) (*WorkflowResult, error)

Run runs the WorkflowInstruction stored at instructions[key], returns results

func (*Workflow) SetCycleCallback

func (wf *Workflow) SetCycleCallback(callback func(from, to string) (bool, error))

SetCycleCallback sets a callback function to be called when a cycle is detected

func (*Workflow) SetCycleHandling

func (wf *Workflow) SetCycleHandling(handling CycleHandling)

SetCycleHandling sets how cycles should be handled

func (*Workflow) SetInstruction

func (wf *Workflow) SetInstruction(name string, i WorkflowInstruction)

SetInstruction sets wf.instructions[name] to the given WorkflowInstruction

func (*Workflow) SetSwarm

func (wf *Workflow) SetSwarm(swarm *Swarm)

SetSwarm sets wf.swarm to the given *Swarm

func (*Workflow) SetTeamLeader

func (wf *Workflow) SetTeamLeader(agentName string, team TeamType) error

SetTeamLeader designates an agent as the leader of a team

func (*Workflow) SetVisualizationHook

func (wf *Workflow) SetVisualizationHook(hook VisualizationHook)

SetVisualizationHook sets the visualization hook for the workflow

type WorkflowInstruction

type WorkflowInstruction func(opts ...any) (*WorkflowResult, error)

WorkflowInstruction represents a function for the Workflow to execute

type WorkflowResult

type WorkflowResult struct {
	Steps       []StepResult
	FinalOutput []llm.Message
	Error       error
	StartTime   time.Time
	EndTime     time.Time
}

WorkflowResult represents the complete workflow execution result

type WorkflowType

type WorkflowType int

WorkflowType defines the type of agent interaction pattern

const (
	CollaborativeWorkflow WorkflowType = iota
	SupervisorWorkflow
	HierarchicalWorkflow
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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