### Install SwarmGo Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Use the go get command to add the package to your project. ```bash go get github.com/prathyushnallamothu/swarmgo ``` -------------------------------- ### Quick Start Agent Execution Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Initialize a Swarm client and run a basic agent interaction. ```go package main import ( "context" "fmt" "log" swarmgo "github.com/prathyushnallamothu/swarmgo" openai "github.com/sashabaranov/go-openai" llm "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { client := swarmgo.NewSwarm("YOUR_OPENAI_API_KEY", llm.OpenAI) agent := &swarmgo.Agent{ Name: "Agent", Instructions: "You are a helpful assistant.", Model: "gpt-3.5-turbo", } messages := []openai.ChatCompletionMessage{ {Role: "user", Content: "Hello!"}, } ctx := context.Background() response, err := client.Run(ctx, agent, messages, nil, "", false, false, 5, true) if err != nil { log.Fatalf("Error: %v", err) } fmt.Println(response.Messages[len(response.Messages)-1].Content) } ``` -------------------------------- ### Implement Custom Stream Handler Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Create a custom stream handler by implementing the StreamHandler interface. This example logs stream events and counts total tokens. ```go type CustomStreamHandler struct { totalTokens int } func (h *CustomStreamHandler) OnStart() { fmt.Println("Starting stream...") } func (h *CustomStreamHandler) OnToken(token string) { h.totalTokens++ fmt.Print(token) } func (h *CustomStreamHandler) OnComplete(msg openai.ChatCompletionMessage) { fmt.Printf("\nComplete! Total tokens: %d\n", h.totalTokens) } func (h *CustomStreamHandler) OnError(err error) { fmt.Printf("Error: %v\n", err) } func (h *CustomStreamHandler) OnToolCall(tool openai.ToolCall) { fmt.Printf("\nUsing tool: %s\n", tool.Function.Name) } ``` -------------------------------- ### Initialize LLM Providers Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Shows how to initialize a Swarm client using either OpenAI or Gemini providers. ```go // Initialize with OpenAI client := swarmgo.NewSwarm("YOUR_API_KEY", llm.OpenAI) // Initialize with Gemini client := swarmgo.NewSwarm("YOUR_API_KEY", llm.Gemini) ``` -------------------------------- ### Create and Configure Agents Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Create agents with instructions, models, and optional functions. Agents can use static instructions or dynamic instructions based on context variables. Supports builder pattern for configuration. ```go package main import ( swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" "fmt" ) func main() { // Basic agent creation agent := &swarmgo.Agent{ Name: "Assistant", Instructions: "You are a helpful assistant.", Model: "gpt-4", } // Using NewAgent with memory store agentWithMemory := swarmgo.NewAgent("MemoryAgent", "gpt-4", llm.OpenAI) agentWithMemory.Instructions = "You are an assistant with memory capabilities." // Using builder pattern builderAgent := swarmgo.NewAgent("BuilderAgent", "gpt-4", llm.OpenAI). WithInstructions("You are a code review assistant."). WithParallelToolCalls(true) // Dynamic instructions based on context dynamicAgent := &swarmgo.Agent{ Name: "DynamicAgent", Model: "gpt-4", InstructionsFunc: func(contextVariables map[string]interface{}) string { name, ok := contextVariables["user_name"].(string) if !ok { name = "User" } return fmt.Sprintf("You are a helpful assistant. Address the user as %s.", name) }, } } ``` -------------------------------- ### Initialize and Configure Collaborative Workflow Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Sets up a new collaborative workflow instance and establishes peer-to-peer connections between agents within a team. ```go workflow := swarmgo.NewWorkflow(apiKey, llm.OpenAI, swarmgo.CollaborativeWorkflow) // Add agents to document team workflow.AddAgentToTeam(editor, swarmgo.DocumentTeam) workflow.AddAgentToTeam(reviewer, swarmgo.DocumentTeam) workflow.AddAgentToTeam(writer, swarmgo.DocumentTeam) // Connect agents in collaborative pattern workflow.ConnectAgents(editor.Name, reviewer.Name) workflow.ConnectAgents(reviewer.Name, writer.Name) workflow.ConnectAgents(writer.Name, editor.Name) ``` -------------------------------- ### Create Collaborative Workflow in Go Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Illustrates setting up a collaborative workflow with writer, editor, and reviewer agents. Requires the OPENAI_API_KEY environment variable. ```go package main import ( "fmt" "log" "os" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { apiKey := os.Getenv("OPENAI_API_KEY") // Peer agents for document processing writerAgent := &swarmgo.Agent{ Name: "WriterAgent", Instructions: "You write content. Pass to EditorAgent for review using 'route to EditorAgent'.", Model: "gpt-4", } editorAgent := &swarmgo.Agent{ Name: "EditorAgent", Instructions: "You edit and improve content. Pass to ReviewerAgent using 'route to ReviewerAgent'.", Model: "gpt-4", } reviewerAgent := &swarmgo.Agent{ Name: "ReviewerAgent", Instructions: "You review final content. If changes needed, route back to WriterAgent. Otherwise mark as 'FINAL:'.", Model: "gpt-4", } // Create collaborative workflow workflow := swarmgo.NewWorkflow(apiKey, llm.OpenAI, swarmgo.CollaborativeWorkflow) // All agents in same team (DocumentTeam) workflow.AddAgentToTeam(writerAgent, swarmgo.DocumentTeam) workflow.AddAgentToTeam(editorAgent, swarmgo.DocumentTeam) workflow.AddAgentToTeam(reviewerAgent, swarmgo.DocumentTeam) // Circular connections for collaboration workflow.ConnectAgents(writerAgent.Name, editorAgent.Name) workflow.ConnectAgents(editorAgent.Name, reviewerAgent.Name) workflow.ConnectAgents(reviewerAgent.Name, writerAgent.Name) // Handle revision cycles workflow.SetCycleHandling(swarmgo.ContinueOnCycle) result, err := workflow.Execute(writerAgent.Name, "Write a blog post about Go programming best practices") if err != nil { log.Fatalf("Error: %v", err) } // Access workflow state fmt.Printf("Current Agent: %s\n", workflow.GetCurrentAgent()) fmt.Printf("Agents: %v\n", workflow.GetAgents()) fmt.Printf("Teams: %v\n", workflow.GetTeams()) // Get specific step results lastStep, _ := workflow.GetLastStepResult() fmt.Printf("Last step by: %s\n", lastStep.AgentName) allSteps := workflow.GetAllStepResults() for _, step := range allSteps { fmt.Printf("Step %d: %s -> %s\n", step.StepNumber, step.AgentName, step.NextAgent) } } ``` -------------------------------- ### Implement Agent Memory Management Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Demonstrates initializing an agent with memory, defining custom functions for storing and recalling facts, and performing direct memory operations like serialization and persistence. ```go package main import ( "context" "fmt" "log" "os" "time" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { client := swarmgo.NewSwarm(os.Getenv("OPENAI_API_KEY"), llm.OpenAI) // Create agent with memory (NewAgent initializes memory store) agent := swarmgo.NewAgent("MemoryAgent", "gpt-4", llm.OpenAI) agent.Instructions = "You are an assistant with memory capabilities." // Add functions for memory operations agent.Functions = []swarmgo.AgentFunction{ { Name: "store_fact", Description: "Store an important fact in memory", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "content": map[string]interface{}{"type": "string", "description": "The fact to remember"}, "importance": map[string]interface{}{"type": "number", "description": "Importance score (0-1)"}, }, "required": []string{"content", "importance"}, }, Function: func(args map[string]interface{}, ctx map[string]interface{}) swarmgo.Result { content := args["content"].(string) importance := args["importance"].(float64) agent.Memory.AddMemory(swarmgo.Memory{ Content: content, Type: "fact", Context: ctx, Timestamp: time.Now(), Importance: importance, }) return swarmgo.Result{Data: fmt.Sprintf("Stored: %s", content)} }, }, { Name: "recall_memories", Description: "Recall stored memories", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "memory_type": map[string]interface{}{"type": "string"}, "count": map[string]interface{}{"type": "number"}, }, "required": []string{"memory_type", "count"}, }, Function: func(args map[string]interface{}, ctx map[string]interface{}) swarmgo.Result { memType := args["memory_type"].(string) count := int(args["count"].(float64)) var memories []swarmgo.Memory if memType == "recent" { memories = agent.Memory.GetRecentMemories(count) } else { memories = agent.Memory.SearchMemories(memType, nil) } var result string for i, mem := range memories { result += fmt.Sprintf("%d. %s (importance: %.2f)\n", i+1, mem.Content, mem.Importance) } return swarmgo.Result{Data: result} }, }, } // Direct memory operations agent.Memory.AddMemory(swarmgo.Memory{ Content: "User prefers dark mode", Type: "preference", Context: map[string]interface{}{"setting": "ui"}, Timestamp: time.Now(), Importance: 0.8, }) // Retrieve recent memories recentMemories := agent.Memory.GetRecentMemories(5) for _, mem := range recentMemories { fmt.Printf("Memory: %s (Type: %s)\n", mem.Content, mem.Type) } // Search by type preferences := agent.Memory.SearchMemories("preference", nil) // Search with context filter uiPrefs := agent.Memory.SearchMemories("preference", map[string]interface{}{"setting": "ui"}) // Serialize memories for persistence data, err := agent.Memory.SerializeMemories() if err == nil { os.WriteFile("memories.json", data, 0644) } // Load memories from file savedData, _ := os.ReadFile("memories.json") agent.Memory.LoadMemories(savedData) // Use agent in conversation ctx := context.Background() messages := []llm.Message{ {Role: llm.RoleUser, Content: "Remember that my favorite color is blue."}, } response, _ := client.Run(ctx, agent, messages, nil, "", false, false, 5, true) fmt.Println(response.Messages[len(response.Messages)-1].Content) } ``` -------------------------------- ### Create an Agent Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Define an agent with a name, instructions, and a specific model. ```go agent := &swarmgo.Agent{ Name: "Agent", Instructions: "You are a helpful assistant.", Model: "gpt-4o", } ``` -------------------------------- ### Create Hierarchical Workflow in Go Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Demonstrates setting up a hierarchical workflow with manager, research, and analysis agents. Ensure the OPENAI_API_KEY environment variable is set. ```go package main import ( "fmt" "log" "os" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { apiKey := os.Getenv("OPENAI_API_KEY") // Manager at top level managerAgent := &swarmgo.Agent{ Name: "ManagerAgent", Instructions: `You are a project manager. Delegate research tasks using "route to ResearchAgent". Review and compile final results.`, Model: "gpt-4", } // Research level researchAgent := &swarmgo.Agent{ Name: "ResearchAgent", Instructions: `You conduct research. Pass findings to analysis using "route to AnalysisAgent".`, Model: "gpt-4", } // Analysis level (leaf) analysisAgent := &swarmgo.Agent{ Name: "AnalysisAgent", Instructions: `You analyze research findings. Report back using "route to ResearchAgent".`, Model: "gpt-4", } // Create hierarchical workflow workflow := swarmgo.NewWorkflow(apiKey, llm.OpenAI, swarmgo.HierarchicalWorkflow) // Add to teams workflow.AddAgentToTeam(managerAgent, swarmgo.SupervisorTeam) workflow.AddAgentToTeam(researchAgent, swarmgo.ResearchTeam) workflow.AddAgentToTeam(analysisAgent, swarmgo.AnalysisTeam) // Set leaders workflow.SetTeamLeader(managerAgent.Name, swarmgo.SupervisorTeam) workflow.SetTeamLeader(researchAgent.Name, swarmgo.ResearchTeam) // Connect in hierarchy: Manager -> Research -> Analysis workflow.ConnectAgents(managerAgent.Name, researchAgent.Name) workflow.ConnectAgents(researchAgent.Name, analysisAgent.Name) workflow.ConnectAgents(analysisAgent.Name, researchAgent.Name) workflow.ConnectAgents(researchAgent.Name, managerAgent.Name) result, err := workflow.Execute(managerAgent.Name, "Research quantum computing applications") if err != nil { log.Fatalf("Error: %v", err) } fmt.Printf("Completed in %d steps\n", len(result.Steps)) } ``` -------------------------------- ### Define LLM Interface Types and Requests in Go Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Demonstrates the initialization of message roles, supported LLM providers, chat completion request structures, and tool call definitions. ```go package main import ( "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { // Message roles systemMsg := llm.Message{Role: llm.RoleSystem, Content: "You are helpful."} userMsg := llm.Message{Role: llm.RoleUser, Content: "Hello"} assistantMsg := llm.Message{Role: llm.RoleAssistant, Content: "Hi there!"} functionMsg := llm.Message{Role: llm.RoleFunction, Content: "result", Name: "myFunc"} toolMsg := llm.Message{Role: llm.RoleTool, Content: "tool result"} // LLM Providers providers := []llm.LLMProvider{ llm.OpenAI, llm.Gemini, llm.Claude, llm.Ollama, llm.DeepSeek, llm.Azure, llm.AzureAD, llm.CloudflareAzure, } // Chat completion request request := llm.ChatCompletionRequest{ Model: "gpt-4", Messages: []llm.Message{systemMsg, userMsg}, Temperature: 0.7, TopP: 1.0, MaxTokens: 2048, PresencePenalty: 0.0, FrequencyPenalty: 0.0, Stop: []string{"\n\n"}, Stream: false, Tools: []llm.Tool{ { Type: "function", Function: &llm.Function{ Name: "get_weather", Description: "Get current weather", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "location": map[string]interface{}{"type": "string"}, }, }, }, }, }, } // Response structure response := llm.ChatCompletionResponse{ ID: "chatcmpl-123", Choices: []llm.Choice{ { Index: 0, Message: assistantMsg, FinishReason: "stop", }, }, Usage: llm.Usage{ PromptTokens: 10, CompletionTokens: 20, TotalTokens: 30, }, } // Tool call structure toolCall := llm.ToolCall{ ID: "call_abc123", Type: "function", Function: llm.ToolCallFunction{ Name: "get_weather", Arguments: `{"location": "NYC"}`, }, } // Message with tool calls msgWithTools := llm.Message{ Role: llm.RoleAssistant, Content: "", ToolCalls: []llm.ToolCall{toolCall}, } } ``` -------------------------------- ### Manage Agent Memory Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Demonstrates initializing an agent with memory, adding custom memory entries, and retrieving or searching stored information. ```go // Create a new agent with memory capabilities agent := swarmgo.NewAgent("MyAgent", "gpt-4") // Memory is automatically managed for conversations and tool calls // You can also explicitly store memories: memory := swarmgo.Memory{ Content: "User prefers dark mode", Type: "preference", Context: map[string]interface{}{"setting": "ui"}, Timestamp: time.Now(), Importance: 0.8, } agent.Memory.AddMemory(memory) // Retrieve recent memories recentMemories := agent.Memory.GetRecentMemories(5) // Search specific types of memories preferences := agent.Memory.SearchMemories("preference", nil) ``` -------------------------------- ### Initialize Swarm Client Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Initialize a Swarm client to interact with LLM providers. The client handles API communication, retries, and configuration. Supports multiple providers and custom configurations. ```go package main import ( "context" "fmt" "log" "os" "time" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { // Initialize with OpenAI client := swarmgo.NewSwarm(os.Getenv("OPENAI_API_KEY"), llm.OpenAI) // Or with other providers geminiClient := swarmgo.NewSwarm(os.Getenv("GEMINI_API_KEY"), llm.Gemini) claudeClient := swarmgo.NewSwarm(os.Getenv("CLAUDE_API_KEY"), llm.Claude) ollamaClient := swarmgo.NewSwarm("", llm.Ollama) // Local Ollama deepseekClient := swarmgo.NewSwarm(os.Getenv("DEEPSEEK_API_KEY"), llm.DeepSeek) // With custom configuration config := &swarmgo.Config{ MaxRetries: 3, RetryBackoff: time.Second, RequestTimeout: 60 * time.Second, MaxTokens: 4096, DefaultModel: "gpt-4", Debug: true, LogLevel: swarmgo.LogInfo, RateLimitStrategy: swarmgo.RateLimitRetry, } customClient := swarmgo.NewSwarmWithConfig(os.Getenv("OPENAI_API_KEY"), llm.OpenAI, config) // With custom host (e.g., Azure OpenAI) azureClient := swarmgo.NewSwarmWithHost(os.Getenv("AZURE_API_KEY"), "https://your-resource.openai.azure.com", llm.OpenAI) // Validate connection if err := client.ValidateConnection(context.Background()); err != nil { log.Fatalf("Connection failed: %v", err) } fmt.Println("Connected successfully") } ``` -------------------------------- ### Define and Use Agent Functions in Go Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Demonstrates defining custom functions for weather and calculation, registering them with a SwarmGo agent, and running the agent with a prompt that utilizes these functions. Ensure the OPENAI_API_KEY environment variable is set. ```go package main import ( "context" "fmt" "log" "os" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) // Define a weather function func getWeather(args map[string]interface{}, contextVariables map[string]interface{}) swarmgo.Result { location := args["location"].(string) time := "now" if t, ok := args["time"].(string); ok { time = t } return swarmgo.Result{ Success: true, Data: fmt.Sprintf(`{"location": "%s", "temperature": "65", "time": "%s"}`, location, time), } } // Define a calculation function func calculate(args map[string]interface{}, contextVariables map[string]interface{}) swarmgo.Result { op := args["operation"].(string) x := args["x"].(float64) y := args["y"].(float64) var result float64 switch op { case "add": result = x + y case "subtract": result = x - y case "multiply": result = x * y case "divide": if y == 0 { return swarmgo.Result{Success: false, Error: fmt.Errorf("division by zero")} } result = x / y } return swarmgo.Result{Success: true, Data: fmt.Sprintf("%.2f", result)} } func main() { client := swarmgo.NewSwarm(os.Getenv("OPENAI_API_KEY"), llm.OpenAI) agent := &swarmgo.Agent{ Name: "ToolAgent", Instructions: "You are a helpful assistant that can check weather and perform calculations.", Model: "gpt-4", Functions: []swarmgo.AgentFunction{ { Name: "getWeather", Description: "Get the current weather in a given location.", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "location": map[string]interface{}{ "type": "string", "description": "The city to get the weather for", }, "time": map[string]interface{}{ "type": "string", "description": "Time for the weather (optional)", }, }, "required": []string{"location"}, }, Function: getWeather, }, { Name: "calculate", Description: "Perform a mathematical calculation", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "operation": map[string]interface{}{ "type": "string", "enum": []string{"add", "subtract", "multiply", "divide"}, }, "x": map[string]interface{}{"type": "number"}, "y": map[string]interface{}{"type": "number"}, }, "required": []string{"operation", "x", "y"}, }, Function: calculate, }, }, } messages := []llm.Message{ {Role: llm.RoleUser, Content: "What's the weather in NYC and what is 42 * 56?"}, } ctx := context.Background() response, err := client.Run(ctx, agent, messages, nil, "", false, false, 5, true) if err != nil { log.Fatalf("Error: %v", err) } // Access tool results for _, toolResult := range response.ToolResults { fmt.Printf("Tool: %s, Args: %v, Result: %v\n", toolResult.ToolName, toolResult.Args, toolResult.Result.Data) } fmt.Println(response.Messages[len(response.Messages)-1].Content) } ``` -------------------------------- ### Implement a Supervisor Workflow in Go Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Defines a supervisor agent to coordinate tasks and worker agents to perform specific duties. Requires setting up agent instructions, team assignments, and routing connections before execution. ```go package main import ( "fmt" "log" "os" "strings" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { apiKey := os.Getenv("OPENAI_API_KEY") // Define supervisor agent supervisorAgent := &swarmgo.Agent{ Name: "SupervisorAgent", Instructions: `You are the SupervisorAgent responsible for coordinating tasks. Your responsibilities: 1. Break down complex tasks into subtasks 2. Assign tasks to appropriate agents using "route to AgentName" 3. Review results and provide final approval with "FINAL_APPROVED:" Use these routing commands: - "route to DataAgent" for data collection - "route to AnalystAgent" for analysis`, Model: "gpt-4", } // Define worker agents dataAgent := &swarmgo.Agent{ Name: "DataAgent", Instructions: `You are responsible for data collection. Format response with: Data Collection Methods, Key Findings, Next Steps. Route back with "route to SupervisorAgent" when complete.`, Model: "gpt-4", } analystAgent := &swarmgo.Agent{ Name: "AnalystAgent", Instructions: `You are responsible for analysis and reporting. Format with: Executive Summary, Detailed Analysis, Recommendations. Use "FINAL_REPORT:" prefix for final reports. Route back with "route to SupervisorAgent" when complete.`, Model: "gpt-4", } // Create supervisor workflow workflow := swarmgo.NewWorkflow(apiKey, llm.OpenAI, swarmgo.SupervisorWorkflow) // Configure cycle handling for revision requests workflow.SetCycleHandling(swarmgo.ContinueOnCycle) workflow.SetCycleCallback(func(from, to string) (bool, error) { fmt.Printf("Cycle detected: %s -> %s\n", from, to) return true, nil // Continue with revision }) // Add agents to teams workflow.AddAgentToTeam(supervisorAgent, swarmgo.SupervisorTeam) workflow.AddAgentToTeam(dataAgent, swarmgo.DocumentTeam) workflow.AddAgentToTeam(analystAgent, swarmgo.AnalysisTeam) // Set team leader workflow.SetTeamLeader(supervisorAgent.Name, swarmgo.SupervisorTeam) // Connect agents workflow.ConnectAgents(supervisorAgent.Name, dataAgent.Name) workflow.ConnectAgents(supervisorAgent.Name, analystAgent.Name) workflow.ConnectAgents(dataAgent.Name, supervisorAgent.Name) workflow.ConnectAgents(analystAgent.Name, supervisorAgent.Name) // Execute workflow task := "Create a report on AI market trends in the tech industry." result, err := workflow.Execute(supervisorAgent.Name, task) if err != nil { log.Fatalf("Workflow error: %v", err) } // Process results fmt.Printf("Total Duration: %v\n", result.EndTime.Sub(result.StartTime)) fmt.Printf("Total Steps: %d\n", len(result.Steps)) for _, step := range result.Steps { fmt.Printf("\nStep %d - Agent: %s\n", step.StepNumber, step.AgentName) fmt.Printf("Duration: %v\n", step.EndTime.Sub(step.StartTime)) if step.Error != nil { fmt.Printf("Error: %v\n", step.Error) } for _, msg := range step.Output { if msg.Role == llm.RoleAssistant { fmt.Printf("Output: %s\n", msg.Content[:min(200, len(msg.Content))]) } } } // Get routing log for _, logEntry := range workflow.GetRoutingLog() { fmt.Println(logEntry) } } func min(a, b int) int { if a < b { return a } return b } ``` -------------------------------- ### Configure Supervisor Workflow Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Sets up a hierarchical supervisor pattern where a lead agent coordinates tasks among worker agents. ```go workflow := swarmgo.NewWorkflow(apiKey, llm.OpenAI, swarmgo.SupervisorWorkflow) // Add agents to teams workflow.AddAgentToTeam(supervisorAgent, swarmgo.SupervisorTeam) workflow.AddAgentToTeam(workerAgent1, swarmgo.WorkerTeam) workflow.AddAgentToTeam(workerAgent2, swarmgo.WorkerTeam) // Set supervisor as team leader workflow.SetTeamLeader(supervisorAgent.Name, swarmgo.SupervisorTeam) // Connect agents workflow.ConnectAgents(supervisorAgent.Name, workerAgent1.Name) workflow.ConnectAgents(supervisorAgent.Name, workerAgent2.Name) ``` -------------------------------- ### Run an Agent Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Execute an agent interaction using the Run method. ```go messages := []openai.ChatCompletionMessage{ {Role: "user", Content: "Hello!"}, } ctx := context.Background() response, err := client.Run(ctx, agent, messages, nil, "", false, false, 5, true) if err != nil { log.Fatalf("Error: %v", err) } fmt.Println(response.Messages[len(response.Messages)-1].Content) ``` -------------------------------- ### Execute Concurrent Agents in Go Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Initializes a ConcurrentSwarm to run multiple analysis agents in parallel. Requires an OpenAI API key and provides methods for both unordered and ordered result retrieval. ```go package main import ( "context" "fmt" "log" "os" "time" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { // Create concurrent swarm cs := swarmgo.NewConcurrentSwarm(os.Getenv("OPENAI_API_KEY"), llm.OpenAI) // Define specialized agents securityAgent := &swarmgo.Agent{ Name: "SecurityAnalyst", Instructions: "You analyze code for security vulnerabilities.", Model: "gpt-4", } performanceAgent := &swarmgo.Agent{ Name: "PerformanceAnalyst", Instructions: "You analyze code for performance issues.", Model: "gpt-4", } styleAgent := &swarmgo.Agent{ Name: "StyleAnalyst", Instructions: "You analyze code for style and best practices.", Model: "gpt-4", } codeToAnalyze := "func processData(input string) { sql.Query(\"SELECT * FROM users WHERE id=\" + input) }" // Configure multiple agents configs := map[string]swarmgo.AgentConfig{ "security": { Agent: securityAgent, Messages: []llm.Message{{Role: llm.RoleUser, Content: "Analyze this code for security: " + codeToAnalyze}}, MaxTurns: 1, ExecuteTools: true, }, "performance": { Agent: performanceAgent, Messages: []llm.Message{{Role: llm.RoleUser, Content: "Analyze this code for performance: " + codeToAnalyze}}, MaxTurns: 1, ExecuteTools: true, }, "style": { Agent: styleAgent, Messages: []llm.Message{{Role: llm.RoleUser, Content: "Analyze this code for style: " + codeToAnalyze}}, MaxTurns: 1, ExecuteTools: true, }, } // Run with timeout ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() results := cs.RunConcurrent(ctx, configs) // Process results for _, result := range results { if result.Error != nil { log.Printf("Error in %s: %v\n", result.AgentName, result.Error) continue } fmt.Printf("\n=== %s Analysis ===\n", result.AgentName) if len(result.Response.Messages) > 0 { fmt.Println(result.Response.Messages[len(result.Response.Messages)-1].Content) } } // Run with ordered results orderedConfigs := []struct { Name string Config swarmgo.AgentConfig }{ {Name: "security", Config: configs["security"]}, {Name: "performance", Config: configs["performance"]}, {Name: "style", Config: configs["style"]}, } orderedResults := cs.RunConcurrentOrdered(ctx, orderedConfigs) for i, result := range orderedResults { fmt.Printf("%d. %s completed\n", i+1, result.AgentName) } } ``` -------------------------------- ### Use Context Variables in Agent Instructions Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Customize agent instructions dynamically using context variables. Ensure the variable is of the expected type; otherwise, a default value is used. ```go func instructions(contextVariables map[string]interface{}) string { name, ok := contextVariables["name"].(string) if !ok { name = "User" } return fmt.Sprintf("You are a helpful assistant. Greet the user by name (%s).", name) } agent.InstructionsFunc = instructions ``` -------------------------------- ### Configure Hierarchical Workflow Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Establishes a tree-like structure for sequential task processing and specialized agent roles. ```go workflow := swarmgo.NewWorkflow(apiKey, llm.OpenAI, swarmgo.HierarchicalWorkflow) // Add agents to teams workflow.AddAgentToTeam(managerAgent, swarmgo.SupervisorTeam) workflow.AddAgentToTeam(researchAgent, swarmgo.ResearchTeam) workflow.AddAgentToTeam(analysisAgent, swarmgo.AnalysisTeam) // Connect agents in hierarchy workflow.ConnectAgents(managerAgent.Name, researchAgent.Name) workflow.ConnectAgents(researchAgent.Name, analysisAgent.Name) ``` -------------------------------- ### Define a Tool Function Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Create a function that returns a swarmgo.Result to be used by an agent. ```go func getWeather(args map[string]interface{}, contextVariables map[string]interface{}) swarmgo.Result { location := args["location"].(string) // Simulate fetching weather data return swarmgo.Result{ Value: fmt.Sprintf(`{"temp": 67, "unit": "F", "location": "%s"}`, location), } } ``` -------------------------------- ### Run Agents Concurrently with SwarmGo Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Execute multiple agents in parallel using ConcurrentSwarm. Configure each agent with its messages and settings, then run them with a context and timeout. ```go // Create a concurrent swarm cs := swarmgo.NewConcurrentSwarm(apiKey) // Configure multiple agents configs := map[string]swarmgo.AgentConfig{ "agent1": { Agent: agent1, Messages: []openai.ChatCompletionMessage{ {Role: openai.ChatMessageRoleUser, Content: "Task 1"}, }, MaxTurns: 1, ExecuteTools: true, }, "agent2": { Agent: agent2, Messages: []openai.ChatCompletionMessage{ {Role: openai.ChatMessageRoleUser, Content: "Task 2"}, }, MaxTurns: 1, ExecuteTools: true, }, } // Run agents concurrently with a timeout ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() results := cs.RunConcurrent(ctx, configs) // Process results for _, result := range results { if result.Error != nil { log.Printf("Error in %s: %v\n", result.AgentName, result.Error) continue } // Handle successful response fmt.Printf("Result from %s: %s\n", result.AgentName, result.Response) } ``` -------------------------------- ### Run Agent Conversations Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Execute agent interactions using the Run method. This sends messages to the agent and returns responses with optional tool execution. Supports context variables and model overrides. ```go package main import ( "context" "fmt" "log" "os" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { client := swarmgo.NewSwarm(os.Getenv("OPENAI_API_KEY"), llm.OpenAI) agent := &swarmgo.Agent{ Name: "Agent", Instructions: "You are a helpful agent.", Model: "gpt-3.5-turbo", } messages := []llm.Message{ {Role: llm.RoleUser, Content: "Hello! How are you today?"}, } ctx := context.Background() // Run parameters: ctx, agent, messages, contextVariables, modelOverride, stream, debug, maxTurns, executeTools response, err := client.Run(ctx, agent, messages, nil, "", false, false, 5, true) if err != nil { log.Fatalf("Error: %v", err) } // Access the response fmt.Printf("Agent: %s\n", response.Messages[len(response.Messages)-1].Content) fmt.Printf("Active Agent: %s\n", response.Agent.Name) // With context variables contextVars := map[string]interface{}{ "user_name": "Alice", "language": "English", } response, err = client.Run(ctx, agent, messages, contextVars, "", false, false, 5, true) // With model override response, err = client.Run(ctx, agent, messages, nil, "gpt-4", false, true, 5, true) } ``` -------------------------------- ### Implement Agent Handoff Function Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Define a function to transfer conversation control to another agent. This function returns a swarmgo.Result object specifying the target agent. ```go func transferToAnotherAgent(args map[string]interface{}, contextVariables map[string]interface{}) swarmgo.Result { anotherAgent := &swarmgo.Agent{ Name: "AnotherAgent", Instructions: "You are another agent.", Model: "gpt-3.5-turbo", } return swarmgo.Result{ Agent: anotherAgent, Value: "Transferring to AnotherAgent.", } } ``` -------------------------------- ### Implement Agent Handoff in Go Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Defines specialized agents and uses transfer functions within a triage agent to route conversations. Requires an OpenAI API key set in the environment. ```go package main import ( "context" "fmt" "log" "os" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) func main() { client := swarmgo.NewSwarm(os.Getenv("OPENAI_API_KEY"), llm.OpenAI) // Create the target agent for handoff spanishAgent := &swarmgo.Agent{ Name: "SpanishAgent", Instructions: "You only speak Spanish. Respond to all messages in Spanish.", Model: "gpt-4", } technicalAgent := &swarmgo.Agent{ Name: "TechnicalAgent", Instructions: "You are a technical support specialist. Help with programming questions.", Model: "gpt-4", } // Transfer functions return the target agent transferToSpanish := func(args map[string]interface{}, contextVariables map[string]interface{}) swarmgo.Result { return swarmgo.Result{ Agent: spanishAgent, Data: "Transferring to Spanish Agent.", } } transferToTechnical := func(args map[string]interface{}, contextVariables map[string]interface{}) swarmgo.Result { return swarmgo.Result{ Agent: technicalAgent, Data: "Transferring to Technical Support.", } } // Main agent with handoff capabilities triageAgent := &swarmgo.Agent{ Name: "TriageAgent", Instructions: "You are a triage agent. Transfer Spanish speakers to SpanishAgent and technical questions to TechnicalAgent.", Model: "gpt-4", Functions: []swarmgo.AgentFunction{ { Name: "transferToSpanishAgent", Description: "Transfer Spanish-speaking users immediately.", Parameters: map[string]interface{}{"type": "object", "properties": map[string]interface{}{}}, Function: transferToSpanish, }, { Name: "transferToTechnicalAgent", Description: "Transfer users with technical programming questions.", Parameters: map[string]interface{}{"type": "object", "properties": map[string]interface{}{}}, Function: transferToTechnical, }, }, } // Test Spanish handoff messages := []llm.Message{ {Role: llm.RoleUser, Content: "Hola, necesito ayuda con mi cuenta."}, } ctx := context.Background() response, err := client.Run(ctx, triageAgent, messages, nil, "", false, false, 5, true) if err != nil { log.Fatalf("Error: %v", err) } fmt.Printf("Active Agent: %s\n", response.Agent.Name) fmt.Printf("Response: %s\n", response.Messages[len(response.Messages)-1].Content) // Output: Active Agent: SpanishAgent } ``` -------------------------------- ### Use Streaming Response with SwarmGo Client Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Initiate a streaming response from an agent using the client's StreamingResponse method. Provide a context, agent, messages, and a custom stream handler. ```go client := swarmgo.NewSwarm("YOUR_OPENAI_API_KEY", llm.OpenAI) agent := &swarmgo.Agent{ Name: "FileAnalyzer", Instructions: "You are an assistant that analyzes files.", Model: "gpt-4", } handler := &CustomStreamHandler{} er := client.StreamingResponse( context.Background(), agent, messages, nil, "", handler, true, ) ``` -------------------------------- ### Implement CustomStreamHandler for real-time responses Source: https://context7.com/prathyushnallamothu/swarmgo/llms.txt Defines a custom handler by implementing the StreamHandler interface to process tokens and tool calls as they arrive from the LLM. ```go package main import ( "context" "fmt" "log" "os" swarmgo "github.com/prathyushnallamothu/swarmgo" "github.com/prathyushnallamothu/swarmgo/llm" ) // CustomStreamHandler implements StreamHandler interface type CustomStreamHandler struct { tokens []string totalCount int } func (h *CustomStreamHandler) OnStart() { fmt.Println("Starting streaming response...") } func (h *CustomStreamHandler) OnToken(token string) { h.tokens = append(h.tokens, token) h.totalCount++ fmt.Print(token) // Print tokens as they arrive } func (h *CustomStreamHandler) OnToolCall(toolCall llm.ToolCall) { fmt.Printf("\nTool called: %s with args: %s\n", toolCall.Function.Name, toolCall.Function.Arguments) } func (h *CustomStreamHandler) OnComplete(message llm.Message) { fmt.Printf("\nComplete! Total tokens: %d\n", h.totalCount) } func (h *CustomStreamHandler) OnError(err error) { fmt.Printf("\nError: %v\n", err) } func main() { client := swarmgo.NewSwarm(os.Getenv("OPENAI_API_KEY"), llm.OpenAI) agent := &swarmgo.Agent{ Name: "StreamAgent", Instructions: "You are a helpful assistant.", Model: "gpt-4", Functions: []swarmgo.AgentFunction{ { Name: "calculate", Description: "Perform a calculation", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "operation": map[string]interface{}{"type": "string"}, "x": map[string]interface{}{"type": "number"}, "y": map[string]interface{}{"type": "number"}, }, "required": []string{"operation", "x", "y"}, }, Function: func(args map[string]interface{}, ctx map[string]interface{}) swarmgo.Result { x, y := args["x"].(float64), args["y"].(float64) return swarmgo.Result{Success: true, Data: fmt.Sprintf("%.2f", x*y)} }, }, }, } messages := []llm.Message{ {Role: llm.RoleUser, Content: "What is 42 multiplied by 56?"}, } handler := &CustomStreamHandler{tokens: make([]string, 0)} ctx := context.Background() // StreamingResponse parameters: ctx, agent, messages, contextVariables, modelOverride, handler, debug err := client.StreamingResponse(ctx, agent, messages, nil, "", handler, false) if err != nil { log.Fatalf("Streaming error: %v", err) } } ``` -------------------------------- ### Add Handoff Function to Agent Source: https://github.com/prathyushnallamothu/swarmgo/blob/master/Readme.md Register a handoff function with an agent by appending it to the agent's Functions slice. This makes the handoff capability available to the agent. ```go agent.Functions = append(agent.Functions, swarmgo.AgentFunction{ Name: "transferToAnotherAgent", Description: "Transfer the conversation to AnotherAgent.", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{}, }, Function: transferToAnotherAgent, }) ```