answer/pkg/agent/context.go
Steve Dudenhoeffer 090b28d956 Update LLM integration and add new agent tools and utilities
Refactored LLM handling to use updated langchaingo models and tools, replacing gollm dependencies. Introduced agent-related utilities, tools, and counters for better modular functionality. Added a parser for LLM model configuration and revamped the answering mechanism with enhanced support for tool-based interaction.
2025-02-25 22:56:32 -05:00

111 lines
2.0 KiB
Go

package agent
import (
"context"
"time"
"github.com/tmc/langchaingo/llms"
)
type Context struct {
context.Context
Messages []llms.MessageContent
Agent *Agent
}
func From(ctx context.Context, a *Agent) *Context {
if ctx == nil {
ctx = context.Background()
}
return &Context{
Context: ctx,
Agent: a,
}
}
func (c *Context) WithMessage(m llms.MessageContent) *Context {
c.Messages = append(c.Messages, m)
return c
}
func (c *Context) WithMessages(m ...llms.MessageContent) *Context {
c.Messages = append(c.Messages, m...)
return c
}
func (c *Context) WithToolResults(r ...ToolResult) *Context {
msg := llms.MessageContent{
Role: llms.ChatMessageTypeTool,
}
for _, v := range r {
res := v.Result
if v.Error != nil {
res = "error executing: " + v.Error.Error()
}
msg.Parts = append(msg.Parts, llms.ToolCallResponse{
ToolCallID: v.ID,
Name: v.Name,
Content: res,
})
}
return c.WithMessage(msg)
}
func (c *Context) WithAgent(a *Agent) *Context {
return &Context{
Context: c.Context,
Agent: a,
}
}
func (c *Context) WithCancel() (*Context, func()) {
ctx, cancel := context.WithCancel(c.Context)
return &Context{
Context: ctx,
Agent: c.Agent,
}, cancel
}
func (c *Context) WithDeadline(deadline time.Time) (*Context, func()) {
ctx, cancel := context.WithDeadline(c.Context, deadline)
return &Context{
Context: ctx,
Agent: c.Agent,
}, cancel
}
func (c *Context) WithTimeout(timeout time.Duration) (*Context, func()) {
ctx, cancel := context.WithTimeout(c.Context, timeout)
return &Context{
Context: ctx,
Agent: c.Agent,
}, cancel
}
func (c *Context) WithValue(key, value interface{}) *Context {
return &Context{
Context: context.WithValue(c.Context, key, value),
Agent: c.Agent,
}
}
func (c *Context) Done() <-chan struct{} {
return c.Context.Done()
}
func (c *Context) Err() error {
return c.Context.Err()
}
func (c *Context) Value(key interface{}) interface{} {
return c.Context.Value(key)
}
func (c *Context) Deadline() (time.Time, bool) {
return c.Context.Deadline()
}