-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
313 lines (279 loc) · 9.35 KB
/
utils.go
File metadata and controls
313 lines (279 loc) · 9.35 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
package agentd
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
adkanthropic "github.com/apzuk3/agentd/model/anthropic"
adkopenai "github.com/apzuk3/agentd/model/openai"
"github.com/google/jsonschema-go/jsonschema"
"google.golang.org/adk/agent"
"google.golang.org/adk/agent/llmagent"
"google.golang.org/adk/agent/workflowagents/loopagent"
"google.golang.org/adk/agent/workflowagents/parallelagent"
"google.golang.org/adk/agent/workflowagents/sequentialagent"
"google.golang.org/adk/model"
"google.golang.org/adk/model/gemini"
"google.golang.org/adk/tool"
"google.golang.org/adk/tool/functiontool"
"google.golang.org/genai"
agentdv1 "github.com/apzuk3/agentd/gen/proto/go/agentd/v1"
)
var openAIPrefixes = []string{"gpt-", "o1", "o3", "o4", "chatgpt-"}
func isOpenAIModel(modelName string) bool {
for _, prefix := range openAIPrefixes {
if strings.HasPrefix(modelName, prefix) {
return true
}
}
return false
}
type modelKeyDiscoverer interface {
APIKeyForModel(modelName string) string
}
// createModel creates an ADK model from a model name string, routing to the
// appropriate provider based on the model name prefix. Returns a structured
// error when the required provider API key is missing.
func createModel(ctx context.Context, modelName string, discoverer modelKeyDiscoverer) (model.LLM, error) {
if strings.HasPrefix(modelName, "claude-") {
anthropicAPIKey := discoverer.APIKeyForModel(modelName)
if anthropicAPIKey == "" {
return nil, fmt.Errorf("Anthropic API key is required for model %q; set ANTHROPIC_API_KEY or pass via %s header", modelName, HeaderAnthropicAPIKey)
}
return adkanthropic.NewModel(ctx, modelName, &adkanthropic.Config{
APIKey: anthropicAPIKey,
Provider: adkanthropic.ProviderAnthropic,
})
}
if isOpenAIModel(modelName) {
openaiAPIKey := discoverer.APIKeyForModel(modelName)
if openaiAPIKey == "" {
return nil, fmt.Errorf("OpenAI API key is required for model %q; set OPENAI_API_KEY or pass via %s header", modelName, HeaderOpenAIAPIKey)
}
return adkopenai.NewModel(ctx, modelName, &adkopenai.Config{APIKey: openaiAPIKey})
}
geminiAPIKey := discoverer.APIKeyForModel(modelName)
if geminiAPIKey == "" {
return nil, fmt.Errorf("Gemini API key is required for model %q; set GEMINI_API_KEY or pass via %s header", modelName, HeaderGeminiAPIKey)
}
return gemini.NewModel(ctx, modelName, &genai.ClientConfig{
APIKey: geminiAPIKey,
})
}
// createTool creates an ADK tool from a proto Tool definition. The returned
// tool proxies execution to the client via sess.DispatchToolCall, blocking
// until the client responds.
func createTool(protoTool *agentdv1.Tool, sess *Session, agentPath []string) (tool.Tool, error) {
cfg := functiontool.Config{
Name: protoTool.GetName(),
Description: protoTool.GetDescription(),
}
if s := protoTool.GetInputSchema(); s != "" {
var schema jsonschema.Schema
if err := json.Unmarshal([]byte(s), &schema); err != nil {
return nil, fmt.Errorf("parsing input schema for tool %q: %w", cfg.Name, err)
}
cfg.InputSchema = &schema
}
path := make([]string, len(agentPath))
copy(path, agentPath)
toolName := protoTool.GetName()
return functiontool.New(cfg, func(ctx tool.Context, args map[string]any) (map[string]any, error) {
argsJSON, err := json.Marshal(args)
if err != nil {
return nil, fmt.Errorf("marshalling tool args: %w", err)
}
resp, err := sess.DispatchToolCall(ctx, ctx.FunctionCallID(), toolName, string(argsJSON), path)
if err != nil {
return nil, err
}
if sd := resp.GetStateDelta(); sd != nil {
for k, v := range sd.AsMap() {
ctx.Actions().StateDelta[k] = v
}
}
switch r := resp.GetResult().(type) {
case *agentdv1.RunRequest_ToolCallResponse_Output:
var result map[string]any
if err := json.Unmarshal([]byte(r.Output), &result); err != nil {
return map[string]any{"result": r.Output}, nil
}
return result, nil
case *agentdv1.RunRequest_ToolCallResponse_Error:
return nil, errors.New(r.Error)
}
return nil, errors.New("empty tool call response")
})
}
// createAgent recursively converts a proto Agent tree into ADK agent objects.
// It populates agentPaths with the path from root to each agent, keyed by name.
// toolCatalog maps tool names to their full proto definitions.
func createAgent(
ctx context.Context,
protoAgent *agentdv1.Agent,
sess *Session,
parentPath []string,
agentPaths map[string][]string,
toolCatalog map[string]*agentdv1.Tool,
builtinCfg *BuiltinToolConfig,
) (agent.Agent, error) {
if protoAgent == nil {
return nil, errors.New("agent definition is nil")
}
name := protoAgent.GetName()
if name == "" {
return nil, errors.New("agent name is required")
}
currentPath := append(append([]string{}, parentPath...), name)
agentPaths[name] = currentPath
switch {
case protoAgent.GetLlm() != nil:
return createLLMAgent(ctx, protoAgent, sess, currentPath, agentPaths, toolCatalog, builtinCfg)
case protoAgent.GetSequential() != nil:
return createSequentialAgent(ctx, protoAgent, sess, currentPath, agentPaths, toolCatalog, builtinCfg)
case protoAgent.GetParallel() != nil:
return createParallelAgent(ctx, protoAgent, sess, currentPath, agentPaths, toolCatalog, builtinCfg)
case protoAgent.GetLoop() != nil:
return createLoopAgent(ctx, protoAgent, sess, currentPath, agentPaths, toolCatalog, builtinCfg)
default:
return nil, fmt.Errorf("agent %q has no agent_type set", name)
}
}
func createLLMAgent(
ctx context.Context,
protoAgent *agentdv1.Agent,
sess *Session,
currentPath []string,
agentPaths map[string][]string,
toolCatalog map[string]*agentdv1.Tool,
builtinCfg *BuiltinToolConfig,
) (agent.Agent, error) {
llm := protoAgent.GetLlm()
m, err := createModel(ctx, llm.GetModel(), sess)
if err != nil {
return nil, fmt.Errorf("creating model for agent %q: %w", protoAgent.GetName(), err)
}
var tools []tool.Tool
for _, name := range llm.GetToolNames() {
pt, ok := toolCatalog[name]
if !ok {
return nil, fmt.Errorf("tool %q referenced by agent %q not found in catalog", name, protoAgent.GetName())
}
t, err := createTool(pt, sess, currentPath)
if err != nil {
return nil, fmt.Errorf("creating tool %q for agent %q: %w", name, protoAgent.GetName(), err)
}
tools = append(tools, t)
}
for _, name := range llm.GetBuiltinTools() {
bt, err := ResolveBuiltinTool(name, builtinCfg)
if err != nil {
return nil, fmt.Errorf("resolving built-in tool %q for agent %q: %w", name, protoAgent.GetName(), err)
}
tools = append(tools, bt)
}
var subAgents []agent.Agent
for _, sa := range llm.GetSubAgents() {
a, err := createAgent(ctx, sa, sess, currentPath, agentPaths, toolCatalog, builtinCfg)
if err != nil {
return nil, fmt.Errorf("creating sub-agent for %q: %w", protoAgent.GetName(), err)
}
subAgents = append(subAgents, a)
}
return llmagent.New(llmagent.Config{
Name: protoAgent.GetName(),
Description: protoAgent.GetDescription(),
Model: m,
Tools: tools,
SubAgents: subAgents,
Instruction: llm.GetInstruction(),
OutputKey: llm.GetOutputKey(),
})
}
func createSequentialAgent(
ctx context.Context,
protoAgent *agentdv1.Agent,
sess *Session,
currentPath []string,
agentPaths map[string][]string,
toolCatalog map[string]*agentdv1.Tool,
builtinCfg *BuiltinToolConfig,
) (agent.Agent, error) {
seq := protoAgent.GetSequential()
subAgents, err := buildSubAgents(ctx, seq.GetAgents(), sess, currentPath, agentPaths, toolCatalog, builtinCfg)
if err != nil {
return nil, err
}
return sequentialagent.New(sequentialagent.Config{
AgentConfig: agent.Config{
Name: protoAgent.GetName(),
Description: protoAgent.GetDescription(),
SubAgents: subAgents,
},
})
}
func createParallelAgent(
ctx context.Context,
protoAgent *agentdv1.Agent,
sess *Session,
currentPath []string,
agentPaths map[string][]string,
toolCatalog map[string]*agentdv1.Tool,
builtinCfg *BuiltinToolConfig,
) (agent.Agent, error) {
par := protoAgent.GetParallel()
subAgents, err := buildSubAgents(ctx, par.GetAgents(), sess, currentPath, agentPaths, toolCatalog, builtinCfg)
if err != nil {
return nil, err
}
return parallelagent.New(parallelagent.Config{
AgentConfig: agent.Config{
Name: protoAgent.GetName(),
Description: protoAgent.GetDescription(),
SubAgents: subAgents,
},
})
}
func createLoopAgent(
ctx context.Context,
protoAgent *agentdv1.Agent,
sess *Session,
currentPath []string,
agentPaths map[string][]string,
toolCatalog map[string]*agentdv1.Tool,
builtinCfg *BuiltinToolConfig,
) (agent.Agent, error) {
loop := protoAgent.GetLoop()
subAgents, err := buildSubAgents(ctx, loop.GetAgents(), sess, currentPath, agentPaths, toolCatalog, builtinCfg)
if err != nil {
return nil, err
}
return loopagent.New(loopagent.Config{
AgentConfig: agent.Config{
Name: protoAgent.GetName(),
Description: protoAgent.GetDescription(),
SubAgents: subAgents,
},
MaxIterations: uint(loop.GetMaxIterations()),
})
}
func buildSubAgents(
ctx context.Context,
protoAgents []*agentdv1.Agent,
sess *Session,
parentPath []string,
agentPaths map[string][]string,
toolCatalog map[string]*agentdv1.Tool,
builtinCfg *BuiltinToolConfig,
) ([]agent.Agent, error) {
var agents []agent.Agent
for _, pa := range protoAgents {
a, err := createAgent(ctx, pa, sess, parentPath, agentPaths, toolCatalog, builtinCfg)
if err != nil {
return nil, err
}
agents = append(agents, a)
}
return agents, nil
}