Repository navigation
fix(adk): flag the function response of a failed tool call with isError #2937
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
fiunchinho
wants to merge
3
commits into
kagent-dev:main
Choose a base branch
from
giantswarm:upstream/adk-tool-error-flag
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+157
−2
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,7 @@ package agent | |
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "os" | ||
| "strings" | ||
|
|
@@ -516,7 +517,8 @@ func makeAfterToolCallback(logger *slog.Logger) llmagent.AfterToolCallback { | |
| } | ||
| } | ||
|
|
||
| // makeOnToolErrorCallback returns an OnToolErrorCallback that logs tool errors. | ||
| // makeOnToolErrorCallback returns an OnToolErrorCallback that logs tool errors | ||
| // and marks the function response of a failed call with isError. | ||
| func makeOnToolErrorCallback(logger *slog.Logger) llmagent.OnToolErrorCallback { | ||
| return func(ctx agent.Context, t tool.Tool, args map[string]any, err error) (map[string]any, error) { | ||
| logger.ErrorContext(ctx, "tool execution failed", "error", err, | ||
|
|
@@ -525,7 +527,11 @@ func makeOnToolErrorCallback(logger *slog.Logger) llmagent.OnToolErrorCallback { | |
| "session_id", ctx.SessionID(), | ||
| "invocation_id", ctx.InvocationID(), | ||
| ) | ||
| return nil, nil | ||
| // A confirmation request is a pause, not a failure; clients match its plain text. | ||
| if errors.Is(err, tool.ErrConfirmationRequired) { | ||
| return nil, nil | ||
| } | ||
| return map[string]any{"error": err.Error(), "isError": true}, nil | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. mcp app tools lose this error text in compaction |
||
| } | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| package agent | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "iter" | ||
| "log/slog" | ||
| "sync" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| adkagent "google.golang.org/adk/v2/agent" | ||
| "google.golang.org/adk/v2/agent/llmagent" | ||
| adkmodel "google.golang.org/adk/v2/model" | ||
| "google.golang.org/adk/v2/runner" | ||
| adksession "google.golang.org/adk/v2/session" | ||
| "google.golang.org/adk/v2/tool" | ||
| "google.golang.org/adk/v2/tool/functiontool" | ||
| "google.golang.org/adk/v2/tool/toolconfirmation" | ||
| "google.golang.org/genai" | ||
| ) | ||
|
|
||
| // The error adk-go's MCP toolset returns for a CallToolResult with IsError set. | ||
| const mcpToolError = "Tool execution failed. Details: bad_data: invalid parameter \"query\": parse error" | ||
|
|
||
| type queryArgs struct { | ||
| Query string `json:"query"` | ||
| } | ||
|
|
||
| // toolCallingModel asks for one call of the tool on its first request and | ||
| // answers with text on every later one, so a turn ends once the function | ||
| // response is in the history. | ||
| type toolCallingModel struct { | ||
| mu sync.Mutex | ||
| requests int | ||
| tool string | ||
| } | ||
|
|
||
| func (m *toolCallingModel) Name() string { return "tool-calling" } | ||
|
|
||
| func (m *toolCallingModel) GenerateContent(_ context.Context, _ *adkmodel.LLMRequest, _ bool) iter.Seq2[*adkmodel.LLMResponse, error] { | ||
| m.mu.Lock() | ||
| m.requests++ | ||
| first := m.requests == 1 | ||
| m.mu.Unlock() | ||
| return func(yield func(*adkmodel.LLMResponse, error) bool) { | ||
| if first { | ||
| yield(&adkmodel.LLMResponse{Content: &genai.Content{Role: genai.RoleModel, Parts: []*genai.Part{{ | ||
| FunctionCall: &genai.FunctionCall{ID: "call-1", Name: m.tool, Args: map[string]any{"query": "up"}}, | ||
| }}}}, nil) | ||
| return | ||
| } | ||
| yield(&adkmodel.LLMResponse{Content: genai.NewContentFromText("done", genai.RoleModel), FinishReason: genai.FinishReasonStop}, nil) | ||
| } | ||
| } | ||
|
|
||
| // toolRunner runs an agent with the tool callbacks createGoogleADKAgent wires, | ||
| // through adk-go's flow, so the tests see the function responses it emits. | ||
| type toolRunner struct { | ||
| runner *runner.Runner | ||
| sessionID string | ||
| } | ||
|
|
||
| func newToolRunner(t *testing.T, ctx context.Context, tools ...tool.Tool) *toolRunner { | ||
| t.Helper() | ||
| log := slog.New(slog.DiscardHandler) | ||
| a, err := llmagent.New(llmagent.Config{ | ||
| Name: "tools", | ||
| Model: &toolCallingModel{tool: tools[0].Name()}, | ||
| Tools: tools, | ||
| BeforeToolCallbacks: []llmagent.BeforeToolCallback{makeBeforeToolCallback(log)}, | ||
| AfterToolCallbacks: []llmagent.AfterToolCallback{makeAfterToolCallback(log)}, | ||
| OnToolErrorCallbacks: []llmagent.OnToolErrorCallback{makeOnToolErrorCallback(log)}, | ||
| }) | ||
| require.NoError(t, err) | ||
| sessions := adksession.InMemoryService() | ||
| r, err := runner.New(runner.Config{AppName: "test", Agent: a, SessionService: sessions}) | ||
| require.NoError(t, err) | ||
| sess, err := sessions.Create(ctx, &adksession.CreateRequest{AppName: "test", UserID: "user"}) | ||
| require.NoError(t, err) | ||
| return &toolRunner{runner: r, sessionID: sess.Session.ID()} | ||
| } | ||
|
|
||
| // turn runs one turn and returns the function responses and function calls | ||
| // the flow emitted, in order. | ||
| func (r *toolRunner) turn(t *testing.T, ctx context.Context, content *genai.Content) (responses []*genai.FunctionResponse, calls []*genai.FunctionCall) { | ||
| t.Helper() | ||
| for event, err := range r.runner.Run(ctx, "user", r.sessionID, content, adkagent.RunConfig{}) { | ||
| require.NoError(t, err) | ||
| if event.Content == nil { | ||
| continue | ||
| } | ||
| for _, part := range event.Content.Parts { | ||
| if part.FunctionResponse != nil { | ||
| responses = append(responses, part.FunctionResponse) | ||
| } | ||
| if part.FunctionCall != nil { | ||
| calls = append(calls, part.FunctionCall) | ||
| } | ||
| } | ||
| } | ||
| return responses, calls | ||
| } | ||
|
|
||
| func TestFailedToolCallIsFlaggedInTheFunctionResponse(t *testing.T) { | ||
| t.Parallel() | ||
| ctx := t.Context() | ||
| failing, err := functiontool.New(functiontool.Config{Name: "query_prometheus"}, func(adkagent.Context, queryArgs) (map[string]any, error) { | ||
| return nil, errors.New(mcpToolError) | ||
| }) | ||
| require.NoError(t, err) | ||
|
|
||
| responses, _ := newToolRunner(t, ctx, failing).turn(t, ctx, genai.NewContentFromText("is prometheus up?", genai.RoleUser)) | ||
|
|
||
| require.Len(t, responses, 1) | ||
| require.Equal(t, "query_prometheus", responses[0].Name) | ||
| require.Equal(t, map[string]any{"error": mcpToolError, "isError": true}, responses[0].Response) | ||
| } | ||
|
|
||
| func TestConfirmationRequestIsAPauseAndRejectionAFailure(t *testing.T) { | ||
| t.Parallel() | ||
| ctx := t.Context() | ||
| ran := false | ||
| guarded, err := functiontool.New(functiontool.Config{Name: "delete_pod", RequireConfirmation: true}, func(adkagent.Context, queryArgs) (map[string]any, error) { | ||
| ran = true | ||
| return map[string]any{"result": "deleted"}, nil | ||
| }) | ||
| require.NoError(t, err) | ||
| r := newToolRunner(t, ctx, guarded) | ||
|
|
||
| responses, calls := r.turn(t, ctx, genai.NewContentFromText("delete the pod", genai.RoleUser)) | ||
|
|
||
| require.Len(t, responses, 1, "the pending call answers with adk-go's plain response") | ||
| require.Contains(t, responses[0].Response, "error") | ||
| require.NotContains(t, responses[0].Response, "isError", "a confirmation request is a pause, not a failure") | ||
| require.Len(t, calls, 2, "the model's call, then the confirmation request") | ||
| require.Equal(t, toolconfirmation.FunctionCallName, calls[1].Name) | ||
|
|
||
| // The user rejects the call: the tool does not run, and the call is flagged. | ||
| rejection := &genai.Content{Role: genai.RoleUser, Parts: []*genai.Part{{FunctionResponse: &genai.FunctionResponse{ | ||
| ID: calls[1].ID, Name: toolconfirmation.FunctionCallName, Response: map[string]any{"confirmed": false}, | ||
| }}}} | ||
| responses, _ = r.turn(t, ctx, rejection) | ||
|
|
||
| require.False(t, ran, "a rejected call must not run") | ||
| require.Len(t, responses, 1) | ||
| require.Equal(t, "delete_pod", responses[0].Name) | ||
| require.Equal(t, map[string]any{"error": "error tool \"delete_pod\" call is rejected", "isError": true}, responses[0].Response) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
our ui already flags error responses, which client?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah, the kagent UI already handles this, this PR changes nothing there. What it does is give the Go ADK the same flag as the other two runtimes, so a client needs one check instead of two shapes (an
errorkey for the Go ADK,isErrorfor the rest). The error key alone is also a weak signal, since a tool that returns a map with an error key as a normal result renders as failed.