logging: pt1

This commit is contained in:
Ettore Di Giacinto
2024-04-15 00:13:10 +02:00
parent ac8f6e94ff
commit f0bc2be678
14 changed files with 118 additions and 126 deletions

View File

@@ -3,6 +3,7 @@ package agent
import ( import (
"context" "context"
"fmt" "fmt"
"log/slog"
"os" "os"
"sync" "sync"
"time" "time"
@@ -34,6 +35,7 @@ type Agent struct {
selfEvaluationInProgress bool selfEvaluationInProgress bool
pause bool pause bool
logger *slog.Logger
newConversations chan openai.ChatCompletionMessage newConversations chan openai.ChatCompletionMessage
} }
@@ -74,12 +76,15 @@ func New(opts ...Option) (*Agent, error) {
} }
} }
if a.options.debugMode { var programLevel = new(slog.LevelVar) // Info by default
fmt.Println("=== Agent in Debug mode ===") h := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: programLevel})
fmt.Println(a.Character.String()) a.logger = slog.New(h)
fmt.Println(a.State().String()) programLevel.Set(a.options.logLevel)
fmt.Println("Permanent goal: ", a.options.permanentGoal)
} a.logger.Info("Agent in Debug mode", "agent", a.Character.Name)
a.logger.Info("Character", "agent", a.Character.Name, "character", a.Character.String())
a.logger.Info("State", "agent", a.Character.Name, "state", a.State().String())
a.logger.Info("Permanent goal", "agent", a.Character.Name, "goal", a.options.permanentGoal)
return a, nil return a, nil
} }
@@ -107,7 +112,7 @@ func (a *Agent) ConversationChannel() chan openai.ChatCompletionMessage {
func (a *Agent) Ask(opts ...JobOption) *JobResult { func (a *Agent) Ask(opts ...JobOption) *JobResult {
a.StopAction() a.StopAction()
j := NewJob(append(opts, WithReasoningCallback(a.options.reasoningCallback), WithResultCallback(a.options.resultCallback))...) j := NewJob(append(opts, WithReasoningCallback(a.options.reasoningCallback), WithResultCallback(a.options.resultCallback))...)
// fmt.Println("Job created", text) // slog.Info("Job created", text)
a.jobQueue <- j a.jobQueue <- j
return j.Result.WaitResult() return j.Result.WaitResult()
} }
@@ -165,10 +170,7 @@ func (a *Agent) runAction(chosenAction Action, decisionResult *decisionResult) (
} }
} }
if a.options.debugMode { a.logger.Info("Running action", "action", chosenAction.Definition().Name, "agent", a.Character.Name)
fmt.Println("Action", chosenAction.Definition().Name)
fmt.Println("Result", result)
}
if chosenAction.Definition().Name.Is(action.StateActionName) { if chosenAction.Definition().Name.Is(action.StateActionName) {
// We need to store the result in the state // We need to store the result in the state
@@ -198,9 +200,7 @@ func (a *Agent) consumeJob(job *Job, role string) {
a.Unlock() a.Unlock()
if paused { if paused {
if a.options.debugMode { a.logger.Info("Agent is paused, skipping job", "agent", a.Character.Name)
fmt.Println("Agent is paused, skipping job")
}
job.Result.Finish(fmt.Errorf("agent is paused")) job.Result.Finish(fmt.Errorf("agent is paused"))
return return
} }
@@ -270,9 +270,8 @@ func (a *Agent) consumeJob(job *Job, role string) {
if userMessage != "" { if userMessage != "" {
results, err := a.options.ragdb.Search(userMessage, a.options.kbResults) results, err := a.options.ragdb.Search(userMessage, a.options.kbResults)
if err != nil { if err != nil {
if a.options.debugMode { a.logger.Info("Error finding similar strings inside KB:", "error", err)
fmt.Println("Error finding similar strings inside KB:", err)
}
// job.Result.Finish(fmt.Errorf("error finding similar strings inside KB: %w", err)) // job.Result.Finish(fmt.Errorf("error finding similar strings inside KB: %w", err))
// return // return
} }
@@ -283,10 +282,8 @@ func (a *Agent) consumeJob(job *Job, role string) {
for _, r := range results { for _, r := range results {
formatResults += fmt.Sprintf("- %s \n", r) formatResults += fmt.Sprintf("- %s \n", r)
} }
if a.options.debugMode { a.logger.Info("Found similar strings in KB", "agent", a.Character.Name, "results", formatResults)
fmt.Println("Found similar strings in KB:")
fmt.Println(formatResults)
}
// a.currentConversation = append(a.currentConversation, // a.currentConversation = append(a.currentConversation,
// openai.ChatCompletionMessage{ // openai.ChatCompletionMessage{
// Role: "system", // Role: "system",
@@ -341,9 +338,7 @@ func (a *Agent) consumeJob(job *Job, role string) {
} }
if chosenAction.Definition().Name.Is(action.StopActionName) { if chosenAction.Definition().Name.Is(action.StopActionName) {
if a.options.debugMode { a.logger.Info("LLM decided to stop")
fmt.Println("LLM decided to stop")
}
job.Result.Finish(nil) job.Result.Finish(nil)
return return
} }
@@ -362,9 +357,7 @@ func (a *Agent) consumeJob(job *Job, role string) {
return return
} }
if a.options.debugMode { a.logger.Info("===> Generating parameters for", "action", chosenAction.Definition().Name)
fmt.Println("===> Generating parameters for", chosenAction.Definition().Name)
}
params, err := a.generateParameters(ctx, pickTemplate, chosenAction, a.currentConversation, reasoning) params, err := a.generateParameters(ctx, pickTemplate, chosenAction, a.currentConversation, reasoning)
if err != nil { if err != nil {
@@ -372,10 +365,8 @@ func (a *Agent) consumeJob(job *Job, role string) {
return return
} }
if a.options.debugMode { a.logger.Info("===> Generated parameters for", "action", chosenAction.Definition().Name)
fmt.Println("===> Generated parameters for", chosenAction.Definition().Name) a.logger.Info(params.actionParams.String())
fmt.Println(params.actionParams.String())
}
if params.actionParams == nil { if params.actionParams == nil {
job.Result.Finish(fmt.Errorf("no parameters")) job.Result.Finish(fmt.Errorf("no parameters"))
@@ -549,9 +540,7 @@ func (a *Agent) consumeJob(job *Job, role string) {
// If we didn't got any message, we can use the response from the action // If we didn't got any message, we can use the response from the action
if chosenAction.Definition().Name.Is(action.ReplyActionName) && msg.Content == "" { if chosenAction.Definition().Name.Is(action.ReplyActionName) && msg.Content == "" {
if a.options.debugMode { a.logger.Info("No output returned from conversation, using the action response as a reply.")
fmt.Println("No output returned from conversation, using the action response as a reply.")
}
msg.Content = replyResponse.Message msg.Content = replyResponse.Message
} }
@@ -570,9 +559,7 @@ func (a *Agent) periodicallyRun() {
// This would be a special action that would be picked up by the agent // This would be a special action that would be picked up by the agent
// and would be used to contact the user. // and would be used to contact the user.
if a.options.debugMode { a.logger.Info("START -- Periodically run is starting")
fmt.Println("START -- Periodically run is starting")
}
if len(a.CurrentConversation()) != 0 { if len(a.CurrentConversation()) != 0 {
// Here the LLM could decide to store some part of the conversation too in the memory // Here the LLM could decide to store some part of the conversation too in the memory
@@ -602,9 +589,8 @@ func (a *Agent) periodicallyRun() {
a.consumeJob(whatNext, SystemRole) a.consumeJob(whatNext, SystemRole)
a.ResetConversation() a.ResetConversation()
if a.options.debugMode { a.logger.Info("STOP -- Periodically run is done")
fmt.Println("STOP -- Periodically run is done")
}
// Save results from state // Save results from state
// a.ResetConversation() // a.ResetConversation()

View File

@@ -2,6 +2,7 @@ package agent_test
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/mudler/local-agent-framework/action" "github.com/mudler/local-agent-framework/action"
. "github.com/mudler/local-agent-framework/agent" . "github.com/mudler/local-agent-framework/agent"
@@ -18,13 +19,13 @@ var _ Action = &TestAction{}
var debugOptions = []JobOption{ var debugOptions = []JobOption{
WithReasoningCallback(func(state ActionCurrentState) bool { WithReasoningCallback(func(state ActionCurrentState) bool {
fmt.Println("Reasoning", state) slog.Info("Reasoning", state)
return true return true
}), }),
WithResultCallback(func(state ActionState) { WithResultCallback(func(state ActionState) {
fmt.Println("Reasoning", state.Reasoning) slog.Info("Reasoning", state.Reasoning)
fmt.Println("Action", state.Action) slog.Info("Action", state.Action)
fmt.Println("Result", state.Result) slog.Info("Result", state.Result)
}), }),
} }
@@ -172,7 +173,6 @@ var _ = Describe("Agent test", func() {
WithLLMAPIURL(apiModel), WithLLMAPIURL(apiModel),
WithModel(testModel), WithModel(testModel),
EnableHUD, EnableHUD,
DebugMode,
// EnableStandaloneJob, // EnableStandaloneJob,
// WithRandomIdentity(), // WithRandomIdentity(),
WithPermanentGoal("I want to learn to play music"), WithPermanentGoal("I want to learn to play music"),
@@ -194,16 +194,15 @@ var _ = Describe("Agent test", func() {
WithLLMAPIURL(apiModel), WithLLMAPIURL(apiModel),
WithModel(testModel), WithModel(testModel),
EnableHUD, EnableHUD,
DebugMode,
EnableStandaloneJob, EnableStandaloneJob,
WithAgentReasoningCallback(func(state ActionCurrentState) bool { WithAgentReasoningCallback(func(state ActionCurrentState) bool {
fmt.Println("Reasoning", state) slog.Info("Reasoning", state)
return true return true
}), }),
WithAgentResultCallback(func(state ActionState) { WithAgentResultCallback(func(state ActionState) {
fmt.Println("Reasoning", state.Reasoning) slog.Info("Reasoning", state.Reasoning)
fmt.Println("Action", state.Action) slog.Info("Action", state.Action)
fmt.Println("Result", state.Result) slog.Info("Result", state.Result)
}), }),
WithActions( WithActions(
&FakeInternetAction{ &FakeInternetAction{
@@ -230,14 +229,12 @@ var _ = Describe("Agent test", func() {
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
go agent.Run() go agent.Run()
defer agent.Stop() defer agent.Stop()
Eventually(func() string { Eventually(func() string {
fmt.Println(agent.State())
return agent.State().Goal return agent.State().Goal
}, "10m", "10s").Should(ContainSubstring("weather"), fmt.Sprint(agent.State())) }, "10m", "10s").Should(ContainSubstring("weather"), fmt.Sprint(agent.State()))
Eventually(func() string { Eventually(func() string {
fmt.Println(agent.State())
return agent.State().String() return agent.State().String()
}, "10m", "10s").Should(ContainSubstring("store"), fmt.Sprint(agent.State())) }, "10m", "10s").Should(ContainSubstring("store"), fmt.Sprint(agent.State()))

View File

@@ -2,6 +2,7 @@ package agent
import ( import (
"context" "context"
"log/slog"
"strings" "strings"
"time" "time"
) )
@@ -20,7 +21,8 @@ type options struct {
randomIdentity bool randomIdentity bool
userActions Actions userActions Actions
enableHUD, standaloneJob, showCharacter, enableKB bool enableHUD, standaloneJob, showCharacter, enableKB bool
debugMode bool
logLevel slog.Level
canStopItself bool canStopItself bool
initiateConversations bool initiateConversations bool
characterfile string characterfile string
@@ -52,6 +54,7 @@ func defaultOptions() *options {
APIURL: "http://localhost:8080", APIURL: "http://localhost:8080",
Model: "echidna", Model: "echidna",
}, },
logLevel: slog.LevelInfo,
character: Character{ character: Character{
Name: "John Doe", Name: "John Doe",
Age: "", Age: "",
@@ -88,6 +91,13 @@ var CanStopItself = func(o *options) error {
return nil return nil
} }
func LogLevel(level slog.Level) Option {
return func(o *options) error {
o.logLevel = level
return nil
}
}
func EnableKnowledgeBaseWithResults(results int) Option { func EnableKnowledgeBaseWithResults(results int) Option {
return func(o *options) error { return func(o *options) error {
o.enableKB = true o.enableKB = true
@@ -101,11 +111,6 @@ var EnableInitiateConversations = func(o *options) error {
return nil return nil
} }
var DebugMode = func(o *options) error {
o.debugMode = true
return nil
}
// EnableStandaloneJob is an option to enable the agent // EnableStandaloneJob is an option to enable the agent
// to run jobs in the background automatically // to run jobs in the background automatically
var EnableStandaloneJob = func(o *options) error { var EnableStandaloneJob = func(o *options) error {

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log/slog"
"os" "os"
"path/filepath" "path/filepath"
"sync" "sync"
@@ -32,7 +33,6 @@ type AgentConfig struct {
Model string `json:"model" form:"model"` Model string `json:"model" form:"model"`
Name string `json:"name" form:"name"` Name string `json:"name" form:"name"`
HUD bool `json:"hud" form:"hud"` HUD bool `json:"hud" form:"hud"`
Debug bool `json:"debug" form:"debug"`
StandaloneJob bool `json:"standalone_job" form:"standalone_job"` StandaloneJob bool `json:"standalone_job" form:"standalone_job"`
RandomIdentity bool `json:"random_identity" form:"random_identity"` RandomIdentity bool `json:"random_identity" form:"random_identity"`
InitiateConversations bool `json:"initiate_conversations" form:"initiate_conversations"` InitiateConversations bool `json:"initiate_conversations" form:"initiate_conversations"`
@@ -175,14 +175,14 @@ func (a *AgentConfig) availableActions(ctx context.Context) []Action {
actions := []Action{} actions := []Action{}
for _, action := range a.Actions { for _, action := range a.Actions {
fmt.Println("Set Action", action) slog.Info("Set Action", action)
var config map[string]string var config map[string]string
if err := json.Unmarshal([]byte(action.Config), &config); err != nil { if err := json.Unmarshal([]byte(action.Config), &config); err != nil {
fmt.Println("Error unmarshalling action config", err) slog.Info("Error unmarshalling action config", err)
continue continue
} }
fmt.Println("Config", config) slog.Info("Config", config)
switch action.Name { switch action.Name {
case ActionSearch: case ActionSearch:
@@ -218,20 +218,20 @@ func (a *AgentConfig) availableConnectors() []Connector {
connectors := []Connector{} connectors := []Connector{}
for _, c := range a.Connector { for _, c := range a.Connector {
fmt.Println("Set Connector", c) slog.Info("Set Connector", c)
var config map[string]string var config map[string]string
if err := json.Unmarshal([]byte(c.Config), &config); err != nil { if err := json.Unmarshal([]byte(c.Config), &config); err != nil {
fmt.Println("Error unmarshalling connector config", err) slog.Info("Error unmarshalling connector config", err)
continue continue
} }
fmt.Println("Config", config) slog.Info("Config", config)
switch c.Type { switch c.Type {
case ConnectorTelegram: case ConnectorTelegram:
cc, err := connector.NewTelegramConnector(config) cc, err := connector.NewTelegramConnector(config)
if err != nil { if err != nil {
fmt.Println("Error creating telegram connector", err) slog.Info("Error creating telegram connector", err)
continue continue
} }
@@ -266,15 +266,15 @@ func (a *AgentPool) startAgentWithConfig(name string, config *AgentConfig) error
connectors := config.availableConnectors() connectors := config.availableConnectors()
fmt.Println("Creating agent", name) slog.Info("Creating agent", name)
fmt.Println("Model", model) slog.Info("Model", model)
fmt.Println("API URL", a.apiURL) slog.Info("API URL", a.apiURL)
actions := config.availableActions(ctx) actions := config.availableActions(ctx)
stateFile, characterFile := a.stateFiles(name) stateFile, characterFile := a.stateFiles(name)
fmt.Println("Actions", actions) slog.Info("Actions", actions)
opts := []Option{ opts := []Option{
WithModel(model), WithModel(model),
WithLLMAPIURL(a.apiURL), WithLLMAPIURL(a.apiURL),
@@ -288,7 +288,7 @@ func (a *AgentPool) startAgentWithConfig(name string, config *AgentConfig) error
WithCharacterFile(characterFile), WithCharacterFile(characterFile),
WithRAGDB(a.ragDB), WithRAGDB(a.ragDB),
WithAgentReasoningCallback(func(state ActionCurrentState) bool { WithAgentReasoningCallback(func(state ActionCurrentState) bool {
fmt.Println("Reasoning", state.Reasoning) slog.Info("Reasoning", state.Reasoning)
manager.Send( manager.Send(
NewMessage( NewMessage(
fmt.Sprintf(`Thinking: %s`, htmlIfy(state.Reasoning)), fmt.Sprintf(`Thinking: %s`, htmlIfy(state.Reasoning)),
@@ -311,7 +311,7 @@ func (a *AgentPool) startAgentWithConfig(name string, config *AgentConfig) error
a.agentStatus[name].addResult(state) a.agentStatus[name].addResult(state)
a.Unlock() a.Unlock()
fmt.Println("Reasoning", state.Reasoning) slog.Info("Reasoning", state.Reasoning)
text := fmt.Sprintf(`Reasoning: %s text := fmt.Sprintf(`Reasoning: %s
Action taken: %+v Action taken: %+v
@@ -337,8 +337,8 @@ func (a *AgentPool) startAgentWithConfig(name string, config *AgentConfig) error
if config.HUD { if config.HUD {
opts = append(opts, EnableHUD) opts = append(opts, EnableHUD)
} }
if config.Debug { if os.Getenv("DEBUG") != "" {
opts = append(opts, DebugMode) opts = append(opts, LogLevel(slog.LevelDebug))
} }
if config.StandaloneJob { if config.StandaloneJob {
opts = append(opts, EnableStandaloneJob) opts = append(opts, EnableStandaloneJob)
@@ -365,8 +365,7 @@ func (a *AgentPool) startAgentWithConfig(name string, config *AgentConfig) error
opts = append(opts, EnableKnowledgeBaseWithResults(config.KnowledgeBaseResults)) opts = append(opts, EnableKnowledgeBaseWithResults(config.KnowledgeBaseResults))
} }
fmt.Println("Starting agent", name) slog.Info("Starting agent", "name", name, "config", config)
fmt.Printf("Config %+v\n", config)
agent, err := New(opts...) agent, err := New(opts...)
if err != nil { if err != nil {
return err return err
@@ -377,7 +376,7 @@ func (a *AgentPool) startAgentWithConfig(name string, config *AgentConfig) error
go func() { go func() {
if err := agent.Run(); err != nil { if err := agent.Run(); err != nil {
fmt.Println("Agent stop: ", err.Error()) slog.Info("Agent stop: ", err.Error())
} }
}() }()

View File

@@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log/slog"
"net/http" "net/http"
"os" "os"
@@ -53,7 +54,7 @@ func (a *App) KnowledgeBaseFile(db *InMemoryDatabase) func(c *fiber.Ctx) error {
return err return err
} }
fmt.Println("File uploaded to: " + destination) slog.Info("File uploaded to: " + destination)
fmt.Printf("Payload: %+v\n", payload) fmt.Printf("Payload: %+v\n", payload)
content, err := readPdf(destination) // Read local pdf file content, err := readPdf(destination) // Read local pdf file
@@ -61,7 +62,7 @@ func (a *App) KnowledgeBaseFile(db *InMemoryDatabase) func(c *fiber.Ctx) error {
panic(err) panic(err)
} }
fmt.Println("Content is", content) slog.Info("Content is", content)
chunkSize := defaultChunkSize chunkSize := defaultChunkSize
if payload.ChunkSize > 0 { if payload.ChunkSize > 0 {
chunkSize = payload.ChunkSize chunkSize = payload.ChunkSize
@@ -130,7 +131,7 @@ func (a *App) Notify(pool *AgentPool) func(c *fiber.Ctx) error {
func (a *App) Delete(pool *AgentPool) func(c *fiber.Ctx) error { func (a *App) Delete(pool *AgentPool) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error { return func(c *fiber.Ctx) error {
if err := pool.Remove(c.Params("name")); err != nil { if err := pool.Remove(c.Params("name")); err != nil {
fmt.Println("Error removing agent", err) slog.Info("Error removing agent", err)
return c.Status(http.StatusInternalServerError).SendString(err.Error()) return c.Status(http.StatusInternalServerError).SendString(err.Error())
} }
return c.Redirect("/agents") return c.Redirect("/agents")
@@ -139,7 +140,7 @@ func (a *App) Delete(pool *AgentPool) func(c *fiber.Ctx) error {
func (a *App) Pause(pool *AgentPool) func(c *fiber.Ctx) error { func (a *App) Pause(pool *AgentPool) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error { return func(c *fiber.Ctx) error {
fmt.Println("Pausing agent", c.Params("name")) slog.Info("Pausing agent", c.Params("name"))
agent := pool.GetAgent(c.Params("name")) agent := pool.GetAgent(c.Params("name"))
if agent != nil { if agent != nil {
agent.Pause() agent.Pause()
@@ -217,7 +218,7 @@ func (a *App) ImportAgent(pool *AgentPool) func(c *fiber.Ctx) error {
return err return err
} }
fmt.Println("Importing agent", config.Name) slog.Info("Importing agent", config.Name)
if config.Name == "" { if config.Name == "" {
c.Status(http.StatusBadRequest).SendString("Name is required") c.Status(http.StatusBadRequest).SendString("Name is required")
@@ -257,13 +258,13 @@ func (a *App) Chat(pool *AgentPool) func(c *fiber.Ctx) error {
go func() { go func() {
agent := pool.GetAgent(agentName) agent := pool.GetAgent(agentName)
if agent == nil { if agent == nil {
fmt.Println("Agent not found in pool", c.Params("name")) slog.Info("Agent not found in pool", c.Params("name"))
return return
} }
res := agent.Ask( res := agent.Ask(
WithText(query), WithText(query),
) )
fmt.Println("response is", res.Response) slog.Info("response is", res.Response)
manager.Send( manager.Send(
NewMessage( NewMessage(
chatDiv(res.Response, "blue"), chatDiv(res.Response, "blue"),

View File

@@ -1,7 +1,7 @@
package connector package connector
import ( import (
"fmt" "log/slog"
"strings" "strings"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
@@ -39,7 +39,7 @@ func (d *Discord) Start(a *agent.Agent) {
// Create a new Discord session using the provided bot token. // Create a new Discord session using the provided bot token.
dg, err := discordgo.New(Token) dg, err := discordgo.New(Token)
if err != nil { if err != nil {
fmt.Println("error creating Discord session,", err) slog.Info("error creating Discord session,", err)
return return
} }
@@ -52,7 +52,7 @@ func (d *Discord) Start(a *agent.Agent) {
// Open a websocket connection to Discord and begin listening. // Open a websocket connection to Discord and begin listening.
err = dg.Open() err = dg.Open()
if err != nil { if err != nil {
fmt.Println("error opening connection,", err) slog.Info("error opening connection,", err)
return return
} }
@@ -84,7 +84,7 @@ func (d *Discord) messageCreate(a *agent.Agent) func(s *discordgo.Session, m *di
) )
_, err := s.ChannelMessageSend(m.ChannelID, job.Response) _, err := s.ChannelMessageSend(m.ChannelID, job.Response)
if err != nil { if err != nil {
fmt.Println("error sending message,", err) slog.Info("error sending message,", err)
} }
} }

View File

@@ -2,6 +2,7 @@ package connector
import ( import (
"fmt" "fmt"
"log/slog"
"strings" "strings"
"time" "time"
@@ -57,7 +58,7 @@ func (g *GithubIssues) Start(a *agent.Agent) {
for { for {
select { select {
case <-ticker.C: case <-ticker.C:
fmt.Println("Looking into github issues...") slog.Info("Looking into github issues...")
g.issuesService() g.issuesService()
case <-a.Context().Done(): case <-a.Context().Done():
return return
@@ -79,7 +80,7 @@ func (g *GithubIssues) issuesService() {
g.repository, g.repository,
&github.IssueListByRepoOptions{}) &github.IssueListByRepoOptions{})
if err != nil { if err != nil {
fmt.Println("Error listing issues", err) slog.Info("Error listing issues", err)
} }
for _, issue := range issues { for _, issue := range issues {
// Do something with the issue // Do something with the issue
@@ -99,7 +100,7 @@ func (g *GithubIssues) issuesService() {
} }
if userName == user.GetLogin() { if userName == user.GetLogin() {
fmt.Println("Ignoring issue opened by the bot") slog.Info("Ignoring issue opened by the bot")
continue continue
} }
messages := []openai.ChatCompletionMessage{ messages := []openai.ChatCompletionMessage{
@@ -133,7 +134,7 @@ func (g *GithubIssues) issuesService() {
// if last comment is from the user and mentions the bot username, we must answer // if last comment is from the user and mentions the bot username, we must answer
if comment.User.GetName() != user.GetLogin() && len(comments)-1 == i { if comment.User.GetName() != user.GetLogin() && len(comments)-1 == i {
if strings.Contains(comment.GetBody(), fmt.Sprintf("@%s", user.GetLogin())) { if strings.Contains(comment.GetBody(), fmt.Sprintf("@%s", user.GetLogin())) {
fmt.Println("Bot was mentioned in the last comment") slog.Info("Bot was mentioned in the last comment")
mustAnswer = true mustAnswer = true
} }
} }
@@ -141,9 +142,9 @@ func (g *GithubIssues) issuesService() {
if len(comments) == 0 || !botAnsweredAlready { if len(comments) == 0 || !botAnsweredAlready {
// if no comments, or bot didn't answer yet, we must answer // if no comments, or bot didn't answer yet, we must answer
fmt.Println("No comments, or bot didn't answer yet") slog.Info("No comments, or bot didn't answer yet")
fmt.Println("Comments:", len(comments)) slog.Info("Comments:", len(comments))
fmt.Println("Bot answered already", botAnsweredAlready) slog.Info("Bot answered already", botAnsweredAlready)
mustAnswer = true mustAnswer = true
} }
@@ -163,7 +164,7 @@ func (g *GithubIssues) issuesService() {
}, },
) )
if err != nil { if err != nil {
fmt.Println("Error creating comment", err) slog.Info("Error creating comment", err)
} }
} }
} }

View File

@@ -3,6 +3,7 @@ package connector
import ( import (
"fmt" "fmt"
"log" "log"
"log/slog"
"os" "os"
"strings" "strings"
@@ -60,11 +61,11 @@ func (t *Slack) Start(a *agent.Agent) {
for evt := range client.Events { for evt := range client.Events {
switch evt.Type { switch evt.Type {
case socketmode.EventTypeConnecting: case socketmode.EventTypeConnecting:
fmt.Println("Connecting to Slack with Socket Mode...") slog.Info("Connecting to Slack with Socket Mode...")
case socketmode.EventTypeConnectionError: case socketmode.EventTypeConnectionError:
fmt.Println("Connection failed. Retrying later...") slog.Info("Connection failed. Retrying later...")
case socketmode.EventTypeConnected: case socketmode.EventTypeConnected:
fmt.Println("Connected to Slack with Socket Mode.") slog.Info("Connected to Slack with Socket Mode.")
case socketmode.EventTypeEventsAPI: case socketmode.EventTypeEventsAPI:
eventsAPIEvent, ok := evt.Data.(slackevents.EventsAPIEvent) eventsAPIEvent, ok := evt.Data.(slackevents.EventsAPIEvent)
if !ok { if !ok {
@@ -91,7 +92,7 @@ func (t *Slack) Start(a *agent.Agent) {
if t.channelID == "" && !t.alwaysReply || // If we have set alwaysReply and no channelID if t.channelID == "" && !t.alwaysReply || // If we have set alwaysReply and no channelID
t.channelID != ev.Channel { // If we have a channelID and it's not the same as the event channel t.channelID != ev.Channel { // If we have a channelID and it's not the same as the event channel
// Skip messages from other channels // Skip messages from other channels
fmt.Println("Skipping reply to channel", ev.Channel, t.channelID) slog.Info("Skipping reply to channel", ev.Channel, t.channelID)
continue continue
} }
@@ -123,7 +124,7 @@ func (t *Slack) Start(a *agent.Agent) {
// strip our id from the message // strip our id from the message
message = strings.ReplaceAll(message, "<@"+b.UserID+"> ", "") message = strings.ReplaceAll(message, "<@"+b.UserID+"> ", "")
fmt.Println("Message", message) slog.Info("Message", message)
go func() { go func() {
res := a.Ask( res := a.Ask(

View File

@@ -2,8 +2,8 @@ package main
import ( import (
"embed" "embed"
"fmt"
"log" "log"
"log/slog"
"net/http" "net/http"
"os" "os"
@@ -75,9 +75,9 @@ func main() {
} }
if len(db.Database) > 0 && kbdisableIndexing != "true" { if len(db.Database) > 0 && kbdisableIndexing != "true" {
fmt.Println("Loading knowledgebase from disk, to skip run with KBDISABLEINDEX=true") slog.Info("Loading knowledgebase from disk, to skip run with KBDISABLEINDEX=true")
if err := db.SaveToStore(); err != nil { if err := db.SaveToStore(); err != nil {
fmt.Println("Error storing in the KB", err) slog.Info("Error storing in the KB", err)
} }
} }

View File

@@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"log/slog"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@@ -120,7 +121,7 @@ func getWebPage(url string) (string, error) {
func Sitemap(url string) (res []string, err error) { func Sitemap(url string) (res []string, err error) {
err = sitemap.ParseFromSite(url, func(e sitemap.Entry) error { err = sitemap.ParseFromSite(url, func(e sitemap.Entry) error {
fmt.Println("Sitemap page: " + e.GetLocation()) slog.Info("Sitemap page: " + e.GetLocation())
content, err := getWebPage(e.GetLocation()) content, err := getWebPage(e.GetLocation())
if err == nil { if err == nil {
res = append(res, content) res = append(res, content)
@@ -133,10 +134,10 @@ func Sitemap(url string) (res []string, err error) {
func WebsiteToKB(website string, chunkSize int, db *InMemoryDatabase) { func WebsiteToKB(website string, chunkSize int, db *InMemoryDatabase) {
content, err := Sitemap(website) content, err := Sitemap(website)
if err != nil { if err != nil {
fmt.Println("Error walking sitemap for website", err) slog.Info("Error walking sitemap for website", err)
} }
fmt.Println("Found pages: ", len(content)) slog.Info("Found pages: ", len(content))
fmt.Println("ChunkSize: ", chunkSize) slog.Info("ChunkSize: ", chunkSize)
StringsToKB(db, chunkSize, content...) StringsToKB(db, chunkSize, content...)
} }
@@ -144,9 +145,9 @@ func WebsiteToKB(website string, chunkSize int, db *InMemoryDatabase) {
func StringsToKB(db *InMemoryDatabase, chunkSize int, content ...string) { func StringsToKB(db *InMemoryDatabase, chunkSize int, content ...string) {
for _, c := range content { for _, c := range content {
chunks := splitParagraphIntoChunks(c, chunkSize) chunks := splitParagraphIntoChunks(c, chunkSize)
fmt.Println("chunks: ", len(chunks)) slog.Info("chunks: ", len(chunks))
for _, chunk := range chunks { for _, chunk := range chunks {
fmt.Println("Chunk size: ", len(chunk)) slog.Info("Chunk size: ", len(chunk))
db.AddEntry(chunk) db.AddEntry(chunk)
} }
@@ -154,7 +155,7 @@ func StringsToKB(db *InMemoryDatabase, chunkSize int, content ...string) {
} }
if err := db.SaveToStore(); err != nil { if err := db.SaveToStore(); err != nil {
fmt.Println("Error storing in the KB", err) slog.Info("Error storing in the KB", err)
} }
} }

View File

@@ -91,8 +91,6 @@
<input type="text" name="kb_results" id="kb_results" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-lg border-gray-300 rounded-md bg-gray-700 text-white" placeholder="3"> <input type="text" name="kb_results" id="kb_results" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-lg border-gray-300 rounded-md bg-gray-700 text-white" placeholder="3">
</div> </div>
<label for="debug" class="block text-lg font-medium text-gray-400">Debug</label>
<input type="checkbox" name="debug" id="debug" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-lg border-gray-300 rounded-md bg-gray-700 text-white">
<label for="standalone_job" class="block text-lg font-medium text-gray-400">Standalone Job</label> <label for="standalone_job" class="block text-lg font-medium text-gray-400">Standalone Job</label>
<input type="checkbox" name="standalone_job" id="standalone_job" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-lg border-gray-300 rounded-md bg-gray-700 text-white"> <input type="checkbox" name="standalone_job" id="standalone_job" class="mt-1 focus:ring-indigo-500 focus:border-indigo-500 block w-full shadow-sm sm:text-lg border-gray-300 rounded-md bg-gray-700 text-white">

View File

@@ -3,6 +3,7 @@ package external
import ( import (
"context" "context"
"fmt" "fmt"
"log/slog"
"strings" "strings"
"github.com/google/go-github/v61/github" "github.com/google/go-github/v61/github"
@@ -52,7 +53,7 @@ func (g *GithubIssuesLabeler) Run(params action.ActionParams) (string, error) {
labels, _, err := g.client.Issues.AddLabelsToIssue(g.context, result.Owner, result.Repository, result.IssueNumber, []string{result.Label}) labels, _, err := g.client.Issues.AddLabelsToIssue(g.context, result.Owner, result.Repository, result.IssueNumber, []string{result.Label})
//labelsNames := []string{} //labelsNames := []string{}
for _, l := range labels { for _, l := range labels {
fmt.Println("Label added:", l.Name) slog.Info("Label added:", l.Name)
//labelsNames = append(labelsNames, l.GetName()) //labelsNames = append(labelsNames, l.GetName())
} }

View File

@@ -3,6 +3,7 @@ package external
import ( import (
"context" "context"
"fmt" "fmt"
"log/slog"
"github.com/google/go-github/v61/github" "github.com/google/go-github/v61/github"
"github.com/mudler/local-agent-framework/action" "github.com/mudler/local-agent-framework/action"
@@ -49,7 +50,7 @@ func (g *GithubIssueSearch) Run(params action.ActionParams) (string, error) {
resultString = fmt.Sprintf("Error listing issues: %v", err) resultString = fmt.Sprintf("Error listing issues: %v", err)
} }
for _, i := range issues.Issues { for _, i := range issues.Issues {
fmt.Println("Issue found:", i.GetTitle()) slog.Info("Issue found:", i.GetTitle())
resultString += fmt.Sprintf("Issue found: %s\n", i.GetTitle()) resultString += fmt.Sprintf("Issue found: %s\n", i.GetTitle())
resultString += fmt.Sprintf("URL: %s\n", i.GetHTMLURL()) resultString += fmt.Sprintf("URL: %s\n", i.GetHTMLURL())
// resultString += fmt.Sprintf("Body: %s\n", i.GetBody()) // resultString += fmt.Sprintf("Body: %s\n", i.GetBody())

3
external/search.go vendored
View File

@@ -2,6 +2,7 @@ package external
import ( import (
"fmt" "fmt"
"log/slog"
"github.com/mudler/local-agent-framework/action" "github.com/mudler/local-agent-framework/action"
"github.com/sap-nocops/duckduckgogo/client" "github.com/sap-nocops/duckduckgogo/client"
@@ -20,7 +21,7 @@ func NewSearch(config map[string]string) *SearchAction {
} }
} }
fmt.Println("Search action with results: ", intResult) slog.Info("Search action with results: ", intResult)
return &SearchAction{results: intResult} return &SearchAction{results: intResult}
} }