feat(agent): add core agent loop and autonomous scheduler
This commit is contained in:
139
internal/agent/agent.go
Normal file
139
internal/agent/agent.go
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
package agent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.db123.ir/db123/divacode/internal/companion"
|
||||||
|
"git.db123.ir/db123/divacode/internal/config"
|
||||||
|
"git.db123.ir/db123/divacode/internal/llama"
|
||||||
|
"git.db123.ir/db123/divacode/internal/memory"
|
||||||
|
"git.db123.ir/db123/divacode/internal/storage"
|
||||||
|
"git.db123.ir/db123/divacode/internal/tools"
|
||||||
|
"git.db123.ir/db123/divacode/pkg/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Agent struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
cfg *config.Config
|
||||||
|
llm *llama.Client
|
||||||
|
mem *memory.Store
|
||||||
|
store *storage.DB
|
||||||
|
companion *companion.Engine
|
||||||
|
tools *tools.Registry
|
||||||
|
|
||||||
|
conversationID string
|
||||||
|
messages []types.Message
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(cfg *config.Config, llm *llama.Client, store *storage.DB, mem *memory.Store, comp *companion.Engine, toolReg *tools.Registry) *Agent {
|
||||||
|
return &Agent{
|
||||||
|
cfg: cfg,
|
||||||
|
llm: llm,
|
||||||
|
store: store,
|
||||||
|
mem: mem,
|
||||||
|
companion: comp,
|
||||||
|
tools: toolReg,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Agent) NewConversation() error {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
id := fmt.Sprintf("%x", time.Now().UnixNano())
|
||||||
|
a.conversationID = id
|
||||||
|
a.messages = nil
|
||||||
|
if err := a.store.Exec("INSERT INTO conversations (id) VALUES (?)", id); err != nil {
|
||||||
|
return fmt.Errorf("new conversation: %w", err)
|
||||||
|
}
|
||||||
|
slog.Info("new conversation", "id", id)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Agent) HandleMessage(ctx context.Context, content string) (string, error) {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
|
||||||
|
userMsg := types.Message{
|
||||||
|
ID: fmt.Sprintf("%x", time.Now().UnixNano()),
|
||||||
|
Role: types.RoleUser,
|
||||||
|
Content: content,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
}
|
||||||
|
a.messages = append(a.messages, userMsg)
|
||||||
|
a.saveMessage(userMsg)
|
||||||
|
|
||||||
|
memories, err := a.mem.Search(ctx, content, a.cfg.MemoryTopK)
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("memory search failed", "error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
prompt, err := a.companion.BuildPrompt(ctx, &companion.PromptInput{
|
||||||
|
UserMessage: content,
|
||||||
|
RecentMessages: a.messages,
|
||||||
|
Memories: memories,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("build prompt: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := a.llm.Complete(&llama.CompletionRequest{
|
||||||
|
Prompt: prompt,
|
||||||
|
Temperature: a.cfg.Temperature,
|
||||||
|
TopP: a.cfg.TopP,
|
||||||
|
MaxTokens: a.cfg.MaxTokens,
|
||||||
|
Stream: false,
|
||||||
|
CachePrompt: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("llm complete: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assistantMsg := types.Message{
|
||||||
|
ID: fmt.Sprintf("%x", time.Now().UnixNano()),
|
||||||
|
Role: types.RoleAssistant,
|
||||||
|
Content: resp.Content,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
}
|
||||||
|
a.messages = append(a.messages, assistantMsg)
|
||||||
|
a.saveMessage(assistantMsg)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
if err := a.mem.Store(context.Background(), userMsg.Content, "conversation"); err != nil {
|
||||||
|
slog.Warn("memory store failed", "error", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return resp.Content, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Agent) Messages() []types.Message {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
return a.messages
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Agent) ConversationID() string {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
return a.conversationID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Agent) saveMessage(msg types.Message) {
|
||||||
|
toolCallJSON := ""
|
||||||
|
if msg.ToolCall != nil {
|
||||||
|
b, _ := json.Marshal(msg.ToolCall)
|
||||||
|
toolCallJSON = string(b)
|
||||||
|
}
|
||||||
|
err := a.store.Exec(
|
||||||
|
"INSERT INTO messages (id, conversation_id, role, content, tool_call, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
msg.ID, a.conversationID, string(msg.Role), msg.Content, toolCallJSON, msg.CreatedAt.Format(time.RFC3339),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("failed to save message", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
69
internal/agent/scheduler.go
Normal file
69
internal/agent/scheduler.go
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
package agent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log/slog"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Scheduler struct {
|
||||||
|
agent *Agent
|
||||||
|
interval time.Duration
|
||||||
|
diaryHour int
|
||||||
|
stopCh chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewScheduler(agent *Agent, interval time.Duration, diaryHour int) *Scheduler {
|
||||||
|
return &Scheduler{
|
||||||
|
agent: agent,
|
||||||
|
interval: interval,
|
||||||
|
diaryHour: diaryHour,
|
||||||
|
stopCh: make(chan struct{}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Scheduler) Start(ctx context.Context) {
|
||||||
|
slog.Info("scheduler started", "interval", s.interval)
|
||||||
|
ticker := time.NewTicker(s.interval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
slog.Info("scheduler stopped via context")
|
||||||
|
return
|
||||||
|
case <-s.stopCh:
|
||||||
|
slog.Info("scheduler stopped via signal")
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
s.tick(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Scheduler) Stop() {
|
||||||
|
close(s.stopCh)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Scheduler) tick(ctx context.Context) {
|
||||||
|
mood := s.agent.companion.Mood()
|
||||||
|
lastContact := s.agent.companion.LastContactDuration()
|
||||||
|
trust := s.agent.companion.Trust()
|
||||||
|
|
||||||
|
slog.Debug("scheduler tick", "mood", mood, "lastContact", lastContact, "trust", trust)
|
||||||
|
|
||||||
|
if lastContact > 48*time.Hour && trust > 0.6 {
|
||||||
|
s.agent.companion.QueueAutonomousMessage(
|
||||||
|
"Haven't heard from you in a while. Everything okay?",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.agent.cfg.AutoDiary {
|
||||||
|
hour := time.Now().Hour()
|
||||||
|
if hour >= s.diaryHour || hour < 1 {
|
||||||
|
if err := s.agent.companion.WriteDiary(ctx); err != nil {
|
||||||
|
slog.Warn("diary write failed", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user