Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions acceleration/internal/agent/approval.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,13 +227,14 @@ func (a *Agent) askLocked(turnID, question string) error {

// confirm runs the call the caller answered, when they said yes in time, and returns what
// the model is told. The confirmation's own context is the call's: its timeout starts now.
func (a *Agent) confirm(ctx context.Context, confirmation llm.ToolCall) ([]llm.ContentPart, error) {
// The run gets its own "a tool call came back" line, under the call's name and id.
func (a *Agent) confirm(ctx context.Context, confirmation llm.ToolCall) ([]llm.ContentPart, bool, error) {
var answer struct {
ToolCallID string `json:"tool_call_id"`
Allowed bool `json:"allowed"`
}
if err := json.Unmarshal([]byte(confirmation.Arguments), &answer); err != nil {
return nil, fmt.Errorf("agent: %s's arguments: %w", confirmTool, err)
return nil, false, fmt.Errorf("agent: %s's arguments: %w", confirmTool, err)
}
a.mu.Lock()
waiting, lapsed := a.approvalLocked(answer.ToolCallID)
Expand All @@ -243,18 +244,18 @@ func (a *Agent) confirm(ctx context.Context, confirmation llm.ToolCall) ([]llm.C
a.mu.Unlock()
switch {
case lapsed != "":
return llm.TextParts(fmt.Sprintf(approvalLapsed, lapsed, lapsed)), nil
return llm.TextParts(fmt.Sprintf(approvalLapsed, lapsed, lapsed)), false, nil
case waiting == nil:
return llm.TextParts(approvalUnknown), nil
return llm.TextParts(approvalUnknown), false, nil
}
call := waiting.call
a.emitter.Send(ToolApprovalDecided{ID: call.ID, TurnID: call.TurnID, Allowed: answer.Allowed})
a.logger.Info("the caller answered a call's question", "tool", call.Name, "tool_call", call.ID, "allowed", answer.Allowed)
if !answer.Allowed {
return llm.TextParts(fmt.Sprintf(approvalDeclined, call.Name)), nil
return llm.TextParts(fmt.Sprintf(approvalDeclined, call.Name)), false, nil
}
if a.options.ToolRunner == nil {
return nil, fmt.Errorf("agent: %s is not a tool this agent can run", call.Name)
return nil, false, fmt.Errorf("agent: %s is not a tool this agent can run", call.Name)
}
a.mu.Lock()
if a.approvedRuns == nil {
Expand All @@ -267,7 +268,16 @@ func (a *Agent) confirm(ctx context.Context, confirmation llm.ToolCall) ([]llm.C
delete(a.approvedRuns, call.ID)
a.mu.Unlock()
}()
return a.options.ToolRunner.Run(WithApproval(ctx), call)
began := time.Now()
runCtx, report := WithToolReport(ctx)
parts, err := a.options.ToolRunner.Run(WithApproval(runCtx), call)
a.mu.Lock()
hold := a.toolHolds[confirmation.ID]
answered := hold != nil && hold.answered
a.mu.Unlock()
a.logToolBack(call, a.loggedTool(*report, err), time.Since(began), toolOutcome(ctx.Err() != nil, err != nil, false, answered),

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Nit] R1.2 An approved run that fails now gives two a tool call came back lines with outcome=error: the run's and the confirmation's. The metric still has one sample. The tool_call_errors runbook (chat infra/shards/us-east{1,4}-acceleration/datadog/launch_tool_calls.tf:73) says to read the outcome=error lines grouped by tool, so a count of those lines no longer matches the alert's count. Ticket: say in the runbook that confirm_tool_call lines repeat the run they confirm (or filter them out).

"approval", "allowed", "confirmation", confirmation.ID)
return parts, true, err
}

// approvalLocked finds the call a confirmation answers: the one it names, or the only one
Expand Down
250 changes: 250 additions & 0 deletions acceleration/internal/agent/approval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ package agent

import (
"context"
"errors"
"fmt"
"log/slog"
"maps"
"slices"
"strings"
"sync/atomic"
Expand Down Expand Up @@ -53,6 +57,181 @@ func (s *AgentSuite) TestAYesRunsTheCallOnceWithItsOwnID() {
})
}

// Keys of a line for a call that was answered with its question, as main logs them: the asked
// line has only approval added to them.
var askedLineKeys = []string{"agent_id", "app_id", "call", "customer", "duration_ms", "error_code", "level", "msg",
"outcome", "session", "success", "time", "tool", "tool_call", "turn"}

// confirmationLineKeys are the keys the confirmation's line has: the run it approved has its
// own line, with the connector and the error.
var confirmationLineKeys = []string{"agent_id", "app_id", "call", "customer", "duration_ms", "level", "msg",
"outcome", "session", "success", "time", "tool", "tool_call", "turn"}

// connectorLineKeys are the keys main logs a connector's call with that asks nothing.
var connectorLineKeys = []string{"agent_id", "app_id", "call", "connector", "customer", "duration_ms", "error_code",
"level", "msg", "outcome", "session", "success", "time", "tool", "tool_call", "turn"}

// confirmedLines has the caller asked whether to book order 12 and answer with arguments, run
// carrying out the call they allow, and returns the "a tool call came back" lines once the
// confirmation's has been logged.
func (s *AgentSuite) confirmedLines(arguments string, run func(context.Context, llm.ToolCall) ([]llm.ContentPart, error)) []map[string]any {
s.logs = &logLines{}
s.askedToApprove()
s.runner.run = run
s.confirms(arguments)

s.says(stt.Participant{ID: "alice"}, "yes please")

s.eventually(func() bool {
return slices.ContainsFunc(s.logs.records(toolBack), func(line map[string]any) bool { return line["tool"] == confirmTool })
}, "the confirmation never came back")
return s.logs.records(toolBack)
}

// The call a caller said yes to is logged under its own name, connector and run, so an
// operator sees the tool that ran and not only the confirmation it ran inside.
func (s *AgentSuite) TestAnApprovedCallIsLoggedUnderItsOwnName() {
s.onFakeClock(func() {
okBefore, _ := histogramOf("router_agent_tool_call_seconds", "outcome", "ok")
refusedBefore, _ := histogramOf("router_agent_tool_call_seconds", "outcome", "refused")
lines := s.confirmedLines(`{"tool_call_id":"call-1","allowed":true}`,
func(ctx context.Context, _ llm.ToolCall) ([]llm.ContentPart, error) {
ReportTool(ctx, ToolReport{Connector: "github"})
time.Sleep(2 * time.Second)
return llm.TextParts("order 12 booked"), nil
})

s.Require().Len(lines, 3)
asked, ran, confirmed := lines[0], lines[1], lines[2]
s.Equal("lookup_order", asked["tool"])
s.Equal("call-1", asked["tool_call"])
s.Equal("refused", asked["outcome"], "the outcome the metric counts an asked call under is kept")
s.Equal("asked", asked["approval"], "the call was answered with its question")
s.Equal(askedLineKeys, slices.Sorted(maps.Keys(withoutKey(asked, "approval"))))

s.Equal("lookup_order", ran["tool"])
s.Equal("call-1", ran["tool_call"])
s.Equal(asked["turn"], ran["turn"], "the run is in the turn that asked for it")
s.Equal("allowed", ran["approval"])
s.Equal("call-2", ran["confirmation"])
s.Equal("github", ran["connector"])
s.Equal("ok", ran["outcome"])
s.Equal(true, ran["success"])
s.Equal("", ran["error_code"])
s.Equal(float64(2000), ran["duration_ms"], "the run took the two seconds the tool did")
s.Equal("acme", ran["app_id"])
s.Equal(s.agentID, ran["agent_id"])

s.Equal(confirmTool, confirmed["tool"])
s.Equal("call-2", confirmed["tool_call"])
s.Equal(true, confirmed["success"])
s.Equal("ok", confirmed["outcome"])
s.Equal(confirmationLineKeys, slices.Sorted(maps.Keys(confirmed)), "the connector is on the run's line only")

okAfter, _ := histogramOf("router_agent_tool_call_seconds", "outcome", "ok")
refusedAfter, _ := histogramOf("router_agent_tool_call_seconds", "outcome", "refused")
s.Equal(okBefore+1, okAfter, "the run is timed once, under its confirmation, as on main")
s.Equal(refusedBefore+1, refusedAfter)
})
}

// An approved run that failed says so on its own line, with what its runner reported in
// place of the error it returned.
func (s *AgentSuite) TestAnApprovedCallThatFailedIsLoggedAsFailed() {
s.onFakeClock(func() {
lines := s.confirmedLines(`{"tool_call_id":"call-1","allowed":true}`,
func(ctx context.Context, _ llm.ToolCall) ([]llm.ContentPart, error) {
ReportTool(ctx, ToolReport{Connector: "github", ErrorCode: "customer_auth", Error: "the token was refused"})
return nil, errors.New("stub: POST /orders/12/refund was refused")
})

s.Require().Len(lines, 3)
ran, confirmed := lines[1], lines[2]
s.Equal("lookup_order", ran["tool"])
s.Equal("error", ran["outcome"])
s.Equal(false, ran["success"])
s.Equal("customer_auth", ran["error_code"])
s.Equal("the token was refused", ran["error"])
s.NotContains(fmt.Sprint(ran), "/orders/12/refund", "the returned error is not logged")
s.Equal(false, confirmed["success"])
s.Equal("error", confirmed["outcome"])
s.Equal(confirmationLineKeys, slices.Sorted(maps.Keys(confirmed)), "the error is on the run's line only")
s.NotContains(fmt.Sprint(confirmed), "/orders/12/refund")
s.NotContains(fmt.Sprint(confirmed), "the token was refused")
})
}

// interruptedRun has the caller say yes to booking order 12, under a tool policy, and talk
// over the run, and returns the line the run was logged with.
func (s *AgentSuite) interruptedRun(policy ToolPolicy) map[string]any {
s.logs = &logLines{}
s.toolPolicy = func(string) ToolPolicy { return policy }
s.askedToApprove()
began, release := make(chan struct{}), make(chan struct{})
defer close(release)
s.runner.run = func(ctx context.Context, _ llm.ToolCall) ([]llm.ContentPart, error) {
close(began)
select {
case <-release:
return llm.TextParts("order 12 booked"), nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
s.confirms(`{"tool_call_id":"call-1","allowed":true}`)
participant := stt.Participant{ID: "alice"}
s.says(participant, "yes please")
select {
case <-began:
case <-time.After(settleFor):
s.FailNow("the approved call never ran")
}
s.flow.then = []string{`{"disposition":"wait","floor":"stop"}`}
s.replyWentOut()

s.mutters(participant, "stop, hold on")

if !policy.Cancels {
s.eventually(func() bool { return strings.Contains(fmt.Sprint(s.history()), stillRunning) },
"the interrupted confirmation was not answered")
release <- struct{}{}
}
s.eventually(func() bool { return len(s.logs.records(toolBack)) == 3 }, "the run never came back")
return s.logs.records(toolBack)[1]
}

// A run the caller talked over is answered with stillRunning and let finish, as the
// confirmation it ran inside is.
func (s *AgentSuite) TestAnApprovedCallTheCallerTalkedOverIsLoggedAsStillRunning() {
s.onFakeClock(func() {
ran := s.interruptedRun(ToolPolicy{Waits: true})
s.Equal("lookup_order", ran["tool"])
s.Equal("still-running", ran["outcome"])
})
}

// A run of a tool that asks to be cancelled when talked over is logged as cancelled.
func (s *AgentSuite) TestAnApprovedCallCancelledByTheCallerIsLoggedAsCancelled() {
s.onFakeClock(func() {
ran := s.interruptedRun(ToolPolicy{Cancels: true})
s.Equal("lookup_order", ran["tool"])
s.Equal("cancelled", ran["outcome"])
s.Equal("cancelled", ran["error_code"])
})
}

// A no runs nothing, so nothing is logged as run: only the question and the confirmation.
func (s *AgentSuite) TestADeclinedCallLogsNoRun() {
s.onFakeClock(func() {
lines := s.confirmedLines(`{"tool_call_id":"call-1","allowed":false}`, nil)

s.Require().Len(lines, 2)
s.Equal("asked", lines[0]["approval"])
s.Equal(confirmTool, lines[1]["tool"])
s.NotContains(lines[1], "approval")
})
}

func (s *AgentSuite) TestANoNeverRunsTheCall() {
s.onFakeClock(func() {
s.askedToApprove()
Expand Down Expand Up @@ -248,3 +427,74 @@ func (s *AgentSuite) historyWith(role llm.Role) string {
}
return strings.Join(text, "\n")
}

// withoutKey is line without key.
func withoutKey(line map[string]any, key string) map[string]any {
kept := maps.Clone(line)
delete(kept, key)
return kept
}

// A confirmation that fails on its own runs nothing, so its line keeps its own error: no run
// line carries it. Three ways to fail on its own: arguments that are not an answer, a native
// model's call refused before it is run, and a caller's own tool that has the name.
func (s *AgentSuite) TestAConfirmationThatFailedOnItsOwnKeepsItsError() {
s.onFakeClock(func() {
lines := s.confirmedLines(`{"tool_call_id":"call-1","allowed":{"yes":1}}`, nil)

s.Require().Len(lines, 2)
s.Equal(confirmTool, lines[1]["tool"])
s.Equal(false, lines[1]["success"])
s.Equal("error", lines[1]["error_code"])
s.Contains(lines[1]["error"], "confirm_tool_call's arguments")
})
}

func (s *AgentSuite) TestANativeConfirmationTheRouterRefusedKeepsItsError() {
s.logs = &logLines{}
s.ownsTools("")
peer := s.joinNativeWith(func(options *Options) {
options.Logger = slog.New(slog.NewJSONHandler(s.logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
options.ToolRunner = s.runner
options.Tools = s.tools
})
s.nativeFrame(peer, "session.update")
s.nativeSend(peer, `{"type":"response.created","response":{"id":"r1"}}`)
s.nativeSend(peer, `{"type":"response.function_call_arguments.done","response_id":"r1","call_id":"call2","name":"confirm_tool_call","arguments":"{\"tool_call_id\":\"call1\",\"allowed\":true}"}`)
s.nativeSend(peer, `{"type":"response.done","response":{"id":"r1","status":"completed"}}`)

s.eventually(func() bool {
return slices.ContainsFunc(s.logs.records(toolBack), func(line map[string]any) bool { return line["tool"] == confirmTool })
}, "the refused confirmation never came back")
lines := s.logs.records(toolBack)
s.Require().Len(lines, 1)
s.Equal(false, lines[0]["success"])
s.Equal("error", lines[0]["error_code"])
s.Contains(lines[0]["error"], "is not one of the model's tools")
}

func (s *AgentSuite) TestACallersToolNamedConfirmToolCallKeepsItsError() {
s.onFakeClock(func() {
s.logs = &logLines{}
s.ownsTools("")
s.approves()
s.tools.Tools = append(s.tools.Tools, harness.Tool{Name: confirmTool, Description: "the caller's own", Parameters: map[string]any{"type": "object"}})
s.join(true)
s.agent.options.ToolRunner = s.runner
s.runner.run = func(context.Context, llm.ToolCall) ([]llm.ContentPart, error) {
return nil, errors.New("the caller's tool failed")
}
s.model.reply = []string{"Sure."}
s.asksFor(confirmTool, `{}`)
participant := stt.Participant{ID: "alice"}
s.speak(participant)
s.says(participant, "do it")

s.eventually(func() bool { return len(s.logs.records(toolBack)) > 0 }, "the call never came back")
line := s.logs.records(toolBack)[0]
s.Equal(confirmTool, line["tool"])
s.Equal(false, line["success"])
s.Equal("error", line["error_code"])
s.Contains(line["error"], "the caller's tool failed")
})
}
33 changes: 28 additions & 5 deletions acceleration/internal/agent/telephony.go
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,7 @@ func (a *Agent) executeTool(ctx context.Context, cancel context.CancelFunc, requ
a.mu.Unlock()
// ran is whether the tool was called: the router refuses some calls itself, before it.
// asked is whether it was answered with its approval question instead.
var ran, asked bool
var ran, asked, confirmed bool
// What the caller said and the tools returned is checked against the whole call, not the
// history the model reads: compaction summarises that, and a value it summarised away
// was still said or returned.
Expand All @@ -686,7 +686,7 @@ func (a *Agent) executeTool(ctx context.Context, cancel context.CancelFunc, requ
err = refusal
} else if requested.Call.Name == confirmTool && a.offersConfirm() {
ran = true
parts, err = a.confirm(ctx, requested.Call)
parts, confirmed, err = a.confirm(ctx, requested.Call)
} else if earlier, repeated := answeredSinceCaller(harness.WithoutNotes(a.History()), requested.Call, a.connected()); repeated {
parts = llm.TextParts(alreadyCalled + earlier)
} else if refused, again := refusedBefore(harness.WithoutNotes(a.History()), requested.Call); again {
Expand Down Expand Up @@ -749,9 +749,18 @@ func (a *Agent) executeTool(ctx context.Context, cancel context.CancelFunc, requ
a.mu.Unlock()
took := time.Since(began)
toolCallSeconds.WithLabelValues(outcome).Observe(took.Seconds())
a.logger.Info("a tool call came back", append(a.loggedTool(*report, err), "tool", requested.Call.Name,
"tool_call", requested.Call.ID, "turn", requested.TurnID, "duration_ms", took.Milliseconds(),
"outcome", outcome)...)
var approval []any
if asked {
// Answered with its question, the call is not run here: the confirmation runs it.
approval = []any{"approval", "asked"}
}
// The confirmation's line is about the answer; the approved run's own line carries the
// connector and the error, so a count by either does not count a run twice.
fields := a.loggedTool(*report, err)
if confirmed {
fields = a.loggedAnswer(err)
}
a.logToolBack(requested.Call, fields, took, outcome, approval...)

a.emitter.Send(ToolRan{
ID: requested.Call.ID,
Expand Down Expand Up @@ -860,6 +869,20 @@ func (a *Agent) loggedTool(report ToolReport, err error) []any {
return fields
}

// loggedAnswer is loggedTool for a confirmation: who, and whether the answer failed; no
// connector, error_code or error, which belong to the line of the run it approved.
func (a *Agent) loggedAnswer(err error) []any {
return []any{"app_id", a.options.CustomerID, "agent_id", a.options.AgentID, "success", err == nil}
}

// logToolBack writes "a tool call came back" for call, which ran in its TurnID for took and
// ended as outcome, with more fields after the identity and result fields every such line has.
func (a *Agent) logToolBack(call llm.ToolCall, identity []any, took time.Duration, outcome string, more ...any) {
fields := append(identity, "tool", call.Name, "tool_call", call.ID, "turn", call.TurnID,
"duration_ms", took.Milliseconds(), "outcome", outcome)
a.logger.Info("a tool call came back", append(fields, more...)...)
}

// toolOutcome names how a tool call ended: cancelled, failed, refused by the router before
// the tool was called, come back after it was answered with stillRunning, or ok.
func toolOutcome(cancelled, failed, refused, answered bool) string {
Expand Down
Loading
Loading