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
|
// Copyright 2025 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package aflow
import (
"fmt"
"maps"
"reflect"
"github.com/google/syzkaller/pkg/aflow/trajectory"
"google.golang.org/genai"
)
type LLMAgent struct {
// For logging/debugging.
Name string
// Name of the state variable to store the final reply of the agent.
// These names can be used in subsequent action instructions/prompts,
// and as final workflow outputs.
Reply string
// Optional additional structured outputs besides the final text reply.
// Use LLMOutputs function to create it.
Outputs *llmOutputs
// Value that controls the degree of randomness in token selection.
// Lower temperatures are good for prompts that require a less open-ended or creative response,
// while higher temperatures can lead to more diverse or creative results.
// Must be assigned a float32 value in the range [0, 2].
Temperature any
// Instructions for the agent.
// Formatted as text/template, can use "{{.Variable}}" as placeholders for dynamic content.
// Variables can come from the workflow inputs, or from preceding actions outputs.
Instruction string
// Prompt for the agent. The same format as Instruction.
Prompt string
// Set of tools for the agent to use.
Tools []Tool
}
// Tool represents a custom tool an LLMAgent can invoke.
// Use NewFuncTool to create function-based tools.
type Tool interface {
verify(*verifyContext)
declaration() *genai.FunctionDeclaration
execute(*Context, map[string]any) (map[string]any, error)
}
// LLMOutputs creates a special tool that can be used by LLM to provide structured outputs.
func LLMOutputs[Args any]() *llmOutputs {
return &llmOutputs{
tool: NewFuncTool("set-results", func(ctx *Context, state struct{}, args Args) (Args, error) {
return args, nil
}, "Use this tool to provide results of the analysis."),
provideOutputs: func(ctx *verifyContext, who string) {
provideOutputs[Args](ctx, who)
},
instruction: `
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
`,
}
}
type llmOutputs struct {
tool Tool
provideOutputs func(*verifyContext, string)
instruction string
}
func (a *LLMAgent) execute(ctx *Context) error {
cfg, instruction, tools := a.config(ctx)
span := &trajectory.Span{
Type: trajectory.SpanAgent,
Name: a.Name,
Instruction: instruction,
Prompt: formatTemplate(a.Prompt, ctx.state),
}
if err := ctx.startSpan(span); err != nil {
return err
}
reply, outputs, err := a.chat(ctx, cfg, tools, span.Prompt)
span.Reply = reply
span.Results = outputs
return ctx.finishSpan(span, err)
}
func (a *LLMAgent) chat(ctx *Context, cfg *genai.GenerateContentConfig, tools map[string]Tool, prompt string) (
string, map[string]any, error) {
var outputs map[string]any
req := []*genai.Content{genai.NewContentFromText(prompt, genai.RoleUser)}
for {
reqSpan := &trajectory.Span{
Type: trajectory.SpanLLM,
Name: a.Name,
}
if err := ctx.startSpan(reqSpan); err != nil {
return "", nil, err
}
resp, err := ctx.generateContent(cfg, req)
if err != nil {
return "", nil, ctx.finishSpan(reqSpan, err)
}
reply, thoughts, calls, respErr := a.parseResponse(resp)
reqSpan.Thoughts = thoughts
if err := ctx.finishSpan(reqSpan, respErr); err != nil {
return "", nil, err
}
if len(calls) == 0 {
// This is the final reply.
if a.Outputs != nil && outputs == nil {
return "", nil, fmt.Errorf("LLM did not call tool to set outputs")
}
ctx.state[a.Reply] = reply
maps.Insert(ctx.state, maps.All(outputs))
return reply, outputs, nil
}
// This is not the final reply, LLM asked to execute some tools.
// Append the current reply, and tool responses to the next request.
responses, outputs1, err := a.callTools(ctx, tools, calls)
if err != nil {
return "", nil, err
}
if outputs != nil && outputs1 != nil {
return "", nil, fmt.Errorf("LLM called outputs tool twice")
}
outputs = outputs1
req = append(req, resp.Candidates[0].Content, responses)
}
}
func (a *LLMAgent) config(ctx *Context) (*genai.GenerateContentConfig, string, map[string]Tool) {
instruction := formatTemplate(a.Instruction, ctx.state)
toolList := a.Tools
if a.Outputs != nil {
instruction += a.Outputs.instruction
toolList = append(toolList, a.Outputs.tool)
}
toolMap := make(map[string]Tool)
var tools []*genai.Tool
for _, tool := range toolList {
decl := tool.declaration()
toolMap[decl.Name] = tool
tools = append(tools, &genai.Tool{
FunctionDeclarations: []*genai.FunctionDeclaration{decl}})
}
return &genai.GenerateContentConfig{
ResponseModalities: []string{"TEXT"},
Temperature: genai.Ptr(a.Temperature.(float32)),
SystemInstruction: genai.NewContentFromText(instruction, genai.RoleUser),
Tools: tools,
}, instruction, toolMap
}
func (a *LLMAgent) callTools(ctx *Context, tools map[string]Tool, calls []*genai.FunctionCall) (
*genai.Content, map[string]any, error) {
responses := &genai.Content{
Role: string(genai.RoleUser),
}
var outputs map[string]any
for _, call := range calls {
tool := tools[call.Name]
if tool == nil {
return nil, nil, fmt.Errorf("no tool %q", call.Name)
}
results, err := tool.execute(ctx, call.Args)
if err != nil {
return nil, nil, err
}
responses.Parts = append(responses.Parts, genai.NewPartFromFunctionResponse(call.Name, results))
responses.Parts[len(responses.Parts)-1].FunctionResponse.ID = call.ID
if a.Outputs != nil && tool == a.Outputs.tool {
outputs = results
}
}
return responses, outputs, nil
}
func (a *LLMAgent) parseResponse(resp *genai.GenerateContentResponse) (
reply, thoughts string, calls []*genai.FunctionCall, err error) {
if len(resp.Candidates) == 0 || resp.Candidates[0] == nil {
err = fmt.Errorf("empty model response")
if resp.PromptFeedback != nil {
err = fmt.Errorf("request blocked: %v", resp.PromptFeedback.BlockReasonMessage)
}
return
}
candidate := resp.Candidates[0]
if candidate.Content == nil || len(candidate.Content.Parts) == 0 {
err = fmt.Errorf("%v (%v)", candidate.FinishMessage, candidate.FinishReason)
return
}
// We don't expect to receive these fields now.
// Note: CitationMetadata may be present sometimes, but we don't have uses for it.
if candidate.GroundingMetadata != nil || candidate.LogprobsResult != nil {
err = fmt.Errorf("unexpected reply fields (%+v)", *candidate)
return
}
for _, part := range candidate.Content.Parts {
// We don't expect to receive these now.
if part.VideoMetadata != nil || part.InlineData != nil ||
part.FileData != nil || part.FunctionResponse != nil ||
part.CodeExecutionResult != nil || part.ExecutableCode != nil {
err = fmt.Errorf("unexpected reply part (%+v)", *part)
return
}
if part.FunctionCall != nil {
calls = append(calls, part.FunctionCall)
} else if part.Thought {
thoughts += part.Text
} else {
reply += part.Text
}
}
return
}
func (a *LLMAgent) verify(vctx *verifyContext) {
vctx.requireNotEmpty(a.Name, "Name", a.Name)
vctx.requireNotEmpty(a.Name, "Reply", a.Reply)
if temp, ok := a.Temperature.(int); ok {
a.Temperature = float32(temp)
}
if temp, ok := a.Temperature.(float32); !ok || temp < 0 || temp > 2 {
vctx.errorf(a.Name, "Temperature must have a float32 value in the range [0, 2]")
}
// Verify dataflow. All dynamic variables must be provided by inputs,
// or preceding actions.
a.verifyTemplate(vctx, "Instruction", a.Instruction)
a.verifyTemplate(vctx, "Prompt", a.Prompt)
for _, tool := range a.Tools {
tool.verify(vctx)
}
vctx.provideOutput(a.Name, a.Reply, reflect.TypeFor[string](), true)
if a.Outputs != nil {
a.Outputs.provideOutputs(vctx, a.Name)
}
}
func (a *LLMAgent) verifyTemplate(vctx *verifyContext, what, text string) {
vctx.requireNotEmpty(a.Name, what, text)
vars := make(map[string]reflect.Type)
for name, state := range vctx.state {
vars[name] = state.typ
}
used, err := verifyTemplate(text, vars)
if err != nil {
vctx.errorf(a.Name, "%v: %v", what, err)
}
for name := range used {
vctx.state[name].used = true
}
}
|