-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathagent.go
More file actions
398 lines (334 loc) · 8.56 KB
/
agent.go
File metadata and controls
398 lines (334 loc) · 8.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package agent
import (
"context"
"fmt"
"io"
"go.gearno.de/kit/log"
"go.probo.inc/probo/pkg/llm"
)
const DefaultMaxTurns = 10
type (
Option func(*Agent)
Agent struct {
name string
handoffDescription string
instructions string
instructionsFunc func(ctx context.Context, a *Agent) string
model string
modelSettings ModelSettings
tools []Tool
handoffs []*Handoff
mcpServers []*MCPServer
maxTurns int
maxToolDepth int
client *llm.Client
logger *log.Logger
hooks []RunHooks
agentHooks AgentHooks
inputGuardrails []InputGuardrail
outputGuardrails []OutputGuardrail
session Session
sessionID string
outputType *OutputType
toolUseBehavior ToolUseBehavior
resetToolChoice bool
responseFormat *llm.ResponseFormat
approval *ApprovalConfig
}
)
func New(name string, client *llm.Client, opts ...Option) *Agent {
a := &Agent{
name: name,
client: client,
maxTurns: DefaultMaxTurns,
maxToolDepth: DefaultMaxToolDepth,
toolUseBehavior: RunLLMAgain(),
resetToolChoice: true,
logger: log.NewLogger(log.WithOutput(io.Discard)),
}
for _, opt := range opts {
opt(a)
}
a.logger = a.logger.Named("agent").With(log.String("agent", name))
return a
}
func (a *Agent) Name() string {
return a.name
}
func (a *Agent) AsTool(name, description string) Tool {
return newAgentTool(a, name, description)
}
func (a *Agent) HandoffDescription() string {
return a.handoffDescription
}
// Clone creates a shallow copy of the agent with the given options applied.
func (a *Agent) Clone(opts ...Option) *Agent {
cp := *a
cp.tools = make([]Tool, len(a.tools))
copy(cp.tools, a.tools)
cp.handoffs = make([]*Handoff, len(a.handoffs))
copy(cp.handoffs, a.handoffs)
cp.mcpServers = make([]*MCPServer, len(a.mcpServers))
copy(cp.mcpServers, a.mcpServers)
cp.hooks = make([]RunHooks, len(a.hooks))
copy(cp.hooks, a.hooks)
cp.inputGuardrails = make([]InputGuardrail, len(a.inputGuardrails))
copy(cp.inputGuardrails, a.inputGuardrails)
cp.outputGuardrails = make([]OutputGuardrail, len(a.outputGuardrails))
copy(cp.outputGuardrails, a.outputGuardrails)
if a.approval != nil {
newApproval := ApprovalConfig{
ShouldApprove: a.approval.ShouldApprove,
}
if len(a.approval.ToolNames) > 0 {
newApproval.ToolNames = make([]string, len(a.approval.ToolNames))
copy(newApproval.ToolNames, a.approval.ToolNames)
newApproval.toolNameSet = buildToolNameSet(newApproval.ToolNames)
}
cp.approval = &newApproval
}
for _, opt := range opts {
opt(&cp)
}
return &cp
}
// clone creates a shallow copy suitable for overriding pointer fields
// (e.g. responseFormat) without affecting the original. Slice fields remain
// shared; use the exported Clone method when slice mutations are needed.
func (a *Agent) clone() *Agent {
cp := *a
return &cp
}
func WithInstructions(s string) Option {
return func(a *Agent) {
a.instructions = s
a.instructionsFunc = nil
}
}
func WithInstructionsFunc(fn func(ctx context.Context, a *Agent) string) Option {
return func(a *Agent) {
a.instructionsFunc = fn
a.instructions = ""
}
}
func WithHandoffDescription(desc string) Option {
return func(a *Agent) {
a.handoffDescription = desc
}
}
func WithModel(m string) Option {
return func(a *Agent) {
a.model = m
}
}
func WithModelSettings(s ModelSettings) Option {
return func(a *Agent) {
a.modelSettings = s
}
}
func WithTools(tools ...Tool) Option {
return func(a *Agent) {
a.tools = append(a.tools, tools...)
}
}
func WithHandoffs(agents ...*Agent) Option {
return func(a *Agent) {
for _, ag := range agents {
if ag != nil {
a.handoffs = append(a.handoffs, &Handoff{Agent: ag})
}
}
}
}
func WithHandoffConfigs(handoffs ...*Handoff) Option {
return func(a *Agent) {
for _, h := range handoffs {
if h != nil && h.Agent != nil {
a.handoffs = append(a.handoffs, h)
}
}
}
}
func WithMaxTurns(n int) Option {
return func(a *Agent) {
if n < 1 {
n = 1
}
a.maxTurns = n
}
}
func WithMaxToolDepth(n int) Option {
return func(a *Agent) {
if n < 1 {
n = 1
}
a.maxToolDepth = n
}
}
func WithTemperature(t float64) Option {
return func(a *Agent) {
a.modelSettings.Temperature = &t
}
}
func WithTopP(p float64) Option {
return func(a *Agent) {
a.modelSettings.TopP = &p
}
}
func WithFrequencyPenalty(p float64) Option {
return func(a *Agent) {
a.modelSettings.FrequencyPenalty = &p
}
}
func WithPresencePenalty(p float64) Option {
return func(a *Agent) {
a.modelSettings.PresencePenalty = &p
}
}
func WithMaxTokens(n int) Option {
return func(a *Agent) {
a.modelSettings.MaxTokens = &n
}
}
func WithToolChoice(tc llm.ToolChoice) Option {
return func(a *Agent) {
a.modelSettings.ToolChoice = &tc
}
}
func WithParallelToolCalls(enabled bool) Option {
return func(a *Agent) {
a.modelSettings.ParallelToolCalls = &enabled
}
}
func WithThinking(budgetTokens int) Option {
return func(a *Agent) {
a.modelSettings.Thinking = &llm.ThinkingConfig{
Enabled: true,
BudgetTokens: budgetTokens,
}
}
}
func WithLogger(l *log.Logger) Option {
return func(a *Agent) {
a.logger = l
}
}
func WithHooks(hooks ...RunHooks) Option {
return func(a *Agent) {
a.hooks = append(a.hooks, hooks...)
}
}
func WithAgentHooks(hooks AgentHooks) Option {
return func(a *Agent) {
a.agentHooks = hooks
}
}
func WithInputGuardrails(guards ...InputGuardrail) Option {
return func(a *Agent) {
a.inputGuardrails = append(a.inputGuardrails, guards...)
}
}
func WithOutputGuardrails(guards ...OutputGuardrail) Option {
return func(a *Agent) {
a.outputGuardrails = append(a.outputGuardrails, guards...)
}
}
func WithSession(s Session, sessionID string) Option {
return func(a *Agent) {
a.session = s
a.sessionID = sessionID
}
}
func WithOutputType(t *OutputType) Option {
return func(a *Agent) {
a.outputType = t
}
}
func WithToolUseBehavior(b ToolUseBehavior) Option {
return func(a *Agent) {
a.toolUseBehavior = b
}
}
func WithResetToolChoice(reset bool) Option {
return func(a *Agent) {
a.resetToolChoice = reset
}
}
func WithMCPServers(servers ...*MCPServer) Option {
return func(a *Agent) {
for _, s := range servers {
if s != nil {
a.mcpServers = append(a.mcpServers, s)
}
}
}
}
func WithApproval(config ApprovalConfig) Option {
config.toolNameSet = buildToolNameSet(config.ToolNames)
return func(a *Agent) {
a.approval = &config
}
}
func (a *Agent) resolveTools(ctx context.Context) ([]ToolDescriptor, map[string]ToolDescriptor, error) {
var all []ToolDescriptor
for _, t := range a.tools {
all = append(all, t)
}
for _, h := range a.handoffs {
all = append(all, h.tool())
}
for _, s := range a.mcpServers {
mcpTools, err := s.Tools(ctx)
if err != nil {
return nil, nil, fmt.Errorf("cannot resolve MCP tools from %q: %w", s.name, err)
}
for _, t := range mcpTools {
all = append(all, t)
}
}
toolMap := make(map[string]ToolDescriptor, len(all))
for _, t := range all {
name := t.Name()
if _, exists := toolMap[name]; exists {
return nil, nil, fmt.Errorf("cannot resolve tools: duplicate tool name %q", name)
}
toolMap[name] = t
}
return all, toolMap, nil
}
func (a *Agent) buildSystemPrompt(ctx context.Context) string {
instr := a.instructions
if a.instructionsFunc != nil {
instr = a.instructionsFunc(ctx, a)
}
data := systemPromptData{
Instructions: instr,
}
for _, h := range a.handoffs {
desc := h.toolDescription()
if len([]rune(desc)) > 200 {
desc = string([]rune(desc)[:200]) + "..."
}
data.Handoffs = append(
data.Handoffs,
systemPromptHandoff{
Name: h.Agent.name,
Description: desc,
},
)
}
return buildSystemPrompt(data)
}