feat(chat): show tool calls inline and stream replies into one message
Chat returned only the final answer, so a wrong tool choice, a hallucinated action, or a footgun like `systemctl stop` against `restart` was invisible from the conversation. Only text deltas were threaded through the turn, and tool calls executed inside Generate with nowhere to report. Replace the delta callback with gateway.TurnStream, which carries text fragments and completed tool calls on one ordered path from the model loop to the channel. The sequence is the point: a tool line that overtakes the sentence it interrupted describes a turn that never happened. Text-only callers use gateway.DeltaFunc and are unaffected. A tool is reported on its result, never on its call -- the call part carries no outcome yet, so reporting both would list every tool twice, once with nothing to say. Telegram renders it behind [chat.telegram] show_tool_calls, off by default: this is debugging visibility, and it narrates every internal step to provide it. The dashboard always shows it, being the operator's own observability surface; its tool lines are live-only and are not persisted with the conversation. The Telegram live reply changes mechanism, and with it what a frame MEANS. It used to stream through sendMessageDraft: drafts are ephemeral 30-second previews, so a tool call longer than that outlived the preview, and successive frames were observed concatenated with their cursors intact. It now sends one real message and edits it. An update used to be "the next preview of the answer"; it is now "the whole answer as it currently stands, replacing what is there". The cursor is appended at render time and never stored, so exactly one exists and always at the end, and a frame too long for one message is cut to its tail rather than rejected outright. A stopped or failed turn now edits the cursor away instead of leaving it blinking on a message nothing will finish. That cleanup runs on a live context because turnCtx is already dead, and it runs on both failure branches: ai-sdk raises an aborted stream as ErrAborted with ctx.Err() formatted in rather than wrapped, so errors.Is cannot be trusted to tell a /stop from a fault. Closes #467
This commit is contained in:
1 parent
9ef6f41910
commit
0d73f2fa5a
27 files changed
+1492
-179
No files matched your search
@@ -0,0 +1,123 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
)
|
||||
|
||||
// recordingStream captures the turn's reported progress in arrival order.
|
||||
type recordingStream struct {
|
||||
events []string
|
||||
}
|
||||
|
||||
func (s *recordingStream) Delta(text string) {
|
||||
s.events = append(s.events, "text:"+text)
|
||||
}
|
||||
|
||||
func (s *recordingStream) ToolCall(event gateway.ToolCallEvent) {
|
||||
s.events = append(s.events, "tool:"+event.Name+":"+event.Summary())
|
||||
}
|
||||
|
||||
func streamOf(parts ...core.StreamPart) <-chan core.StreamPart {
|
||||
ch := make(chan core.StreamPart, len(parts))
|
||||
for _, part := range parts {
|
||||
ch <- part
|
||||
}
|
||||
close(ch)
|
||||
return ch
|
||||
}
|
||||
|
||||
func TestDrainChatStream(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
parts []core.StreamPart
|
||||
wantText string
|
||||
wantEvents []string
|
||||
}{
|
||||
{
|
||||
name: "text only",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartTextDelta, TextDelta: "hello "},
|
||||
{Type: core.StreamPartTextDelta, TextDelta: "world"},
|
||||
},
|
||||
wantText: "hello world",
|
||||
wantEvents: []string{"text:hello ", "text:world"},
|
||||
},
|
||||
{
|
||||
name: "a tool result is reported between the text around it",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartTextDelta, TextDelta: "checking"},
|
||||
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "1", ToolName: "shell", Input: `{"cmd":"true"}`}},
|
||||
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolCallID: "1", ToolName: "shell", Output: "exit 0"}},
|
||||
{Type: core.StreamPartTextDelta, TextDelta: " done"},
|
||||
},
|
||||
wantText: "checking done",
|
||||
wantEvents: []string{"text:checking", "tool:shell:exit 0", "text: done"},
|
||||
},
|
||||
{
|
||||
name: "a failed tool is reported as a failure, not silence",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "shell", Error: "exit status 2"}},
|
||||
},
|
||||
wantEvents: []string{"tool:shell:failed: exit status 2"},
|
||||
},
|
||||
{
|
||||
// The tool call part carries no outcome yet: reporting it as
|
||||
// well would show every tool twice.
|
||||
name: "the tool call part alone reports nothing",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolName: "shell"}},
|
||||
},
|
||||
wantEvents: nil,
|
||||
},
|
||||
{
|
||||
name: "parts with nothing to render are skipped",
|
||||
parts: []core.StreamPart{
|
||||
{Type: core.StreamPartStartStep},
|
||||
{Type: core.StreamPartTextDelta, TextDelta: ""},
|
||||
{Type: core.StreamPartReasoningDelta, ReasoningDelta: "thinking"},
|
||||
{Type: core.StreamPartToolResult},
|
||||
{Type: core.StreamPartFinishStep},
|
||||
{Type: core.StreamPartFinish},
|
||||
},
|
||||
wantEvents: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
sink := &recordingStream{}
|
||||
text := drainChatStream(streamOf(tc.parts...), sink)
|
||||
|
||||
if text != tc.wantText {
|
||||
t.Fatalf("text = %q, want %q", text, tc.wantText)
|
||||
}
|
||||
if len(sink.events) != len(tc.wantEvents) {
|
||||
t.Fatalf("events = %v, want %v", sink.events, tc.wantEvents)
|
||||
}
|
||||
for i := range tc.wantEvents {
|
||||
if sink.events[i] != tc.wantEvents[i] {
|
||||
t.Fatalf("events = %v, want %v", sink.events, tc.wantEvents)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The stream must be drained to close even when nobody is rendering it:
|
||||
// ai-sdk writes to FullStream synchronously, so an abandoned stream stalls
|
||||
// the generating goroutine.
|
||||
func TestDrainChatStreamWithoutASinkStillCollectsText(t *testing.T) {
|
||||
text := drainChatStream(streamOf(
|
||||
core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "a"},
|
||||
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "shell", Output: "ok"}},
|
||||
core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "b"},
|
||||
), nil)
|
||||
|
||||
if text != "ab" {
|
||||
t.Fatalf("text = %q, want %q", text, "ab")
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,7 @@ func (m *preparedChatTurnModel) ToolSchemaTokens() int {
|
||||
func (m *preparedChatTurnModel) Generate(
|
||||
ctx context.Context,
|
||||
request gateway.TurnModelRequest,
|
||||
onDelta func(string),
|
||||
stream gateway.TurnStream,
|
||||
) (string, error) {
|
||||
options := m.options
|
||||
options.Messages = make([]chat.Message, len(request.Messages))
|
||||
@@ -93,5 +93,5 @@ func (m *preparedChatTurnModel) Generate(
|
||||
options.Messages[i] = chat.Message{Role: role, Content: message.Content}
|
||||
}
|
||||
options.MaxTokens = request.MaxTokens
|
||||
return sendChatTurn(ctx, m.llm, m.model, options, onDelta)
|
||||
return sendChatTurn(ctx, m.llm, m.model, options, stream)
|
||||
}
|
||||
@@ -86,6 +86,7 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o
|
||||
configureTelegramUpdates(tg, s)
|
||||
}
|
||||
tg.Dangerous = s.Dangerous
|
||||
tg.ShowToolCalls = cfg.Chat.Telegram.ShowToolCalls
|
||||
tg.ReleaseAnnouncements = &releaseannounce.Announcer{
|
||||
StatePath: releaseAnnouncementStatePath(cfg.WorkDir, cfg.BotUser),
|
||||
Components: []releaseannounce.Component{
|
||||
@@ -155,7 +156,10 @@ func makeTelegramReload(s telegramSetup) func(*telegram.Gateway) error {
|
||||
}
|
||||
g.Token = token
|
||||
g.AllowedUserIDs = newCfg.Chat.Telegram.AllowedUserIDs
|
||||
s.Log.Info("chat gateway config reloaded", "allowed_user_ids", len(g.AllowedUserIDs))
|
||||
g.ShowToolCalls = newCfg.Chat.Telegram.ShowToolCalls
|
||||
s.Log.Info("chat gateway config reloaded",
|
||||
"allowed_user_ids", len(g.AllowedUserIDs),
|
||||
"show_tool_calls", g.ShowToolCalls)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -232,8 +236,8 @@ func newChatTurnRunner(
|
||||
return runner
|
||||
}
|
||||
|
||||
func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, onDelta func(string)) (string, error) {
|
||||
if onDelta == nil {
|
||||
func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream) (string, error) {
|
||||
if turn == nil {
|
||||
result, err := llm.Chat(ctx, chatModel, options)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("llm chat: %w", err)
|
||||
@@ -244,18 +248,47 @@ func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, o
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("llm chat stream: %w", err)
|
||||
}
|
||||
var sb strings.Builder
|
||||
for part := range stream.FullStream {
|
||||
if part.Type != core.StreamPartTextDelta || part.TextDelta == "" {
|
||||
continue
|
||||
}
|
||||
sb.WriteString(part.TextDelta)
|
||||
onDelta(part.TextDelta)
|
||||
}
|
||||
text := drainChatStream(stream.FullStream, turn)
|
||||
if _, err := stream.FinishReason(); err != nil {
|
||||
return "", fmt.Errorf("llm chat stream: %w", err)
|
||||
}
|
||||
return sb.String(), nil
|
||||
return text, nil
|
||||
}
|
||||
|
||||
// drainChatStream consumes a model stream to close, reporting assistant text
|
||||
// and each completed tool call to turn, and returns the assembled reply.
|
||||
//
|
||||
// FullStream is authoritative and its writes are synchronous, so it must be
|
||||
// drained to close even when turn is nil -- an unread stream stalls the
|
||||
// generating goroutine.
|
||||
//
|
||||
// A tool is reported on its result, never on its call: the call part carries
|
||||
// no outcome yet, so reporting both would show every tool twice, once with
|
||||
// nothing to say.
|
||||
func drainChatStream(parts <-chan core.StreamPart, turn gateway.TurnStream) string {
|
||||
var sb strings.Builder
|
||||
for part := range parts {
|
||||
switch part.Type {
|
||||
case core.StreamPartTextDelta:
|
||||
if part.TextDelta == "" {
|
||||
continue
|
||||
}
|
||||
sb.WriteString(part.TextDelta)
|
||||
if turn != nil {
|
||||
turn.Delta(part.TextDelta)
|
||||
}
|
||||
case core.StreamPartToolResult:
|
||||
if part.ToolResult == nil || turn == nil {
|
||||
continue
|
||||
}
|
||||
turn.ToolCall(gateway.ToolCallEvent{
|
||||
Name: part.ToolResult.ToolName,
|
||||
Output: part.ToolResult.Output,
|
||||
Err: part.ToolResult.Error,
|
||||
})
|
||||
}
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// chatTitleGenerator proposes session titles through the chat model. It
|
||||
|
||||
Reference in new issue
Block a user