feat(agent): name the turn's chat model on the completion event (#4252)

The agent completion event carries the turn's aggregated token usage
but not the chat model that produced it. A relay or gateway that meters
agent chat cannot price that usage: unit prices, and the discounts for
cache reads, cache writes and uncached input, differ per model, and
changing an agent's model blends the old and the new numbers in one
total.

The completion event's data now carries model_id, taken from the
engine's chat model. The turn's usage is aggregated only from calls
made through that model (each round and the final answer), so it names
the model the usage belongs to. A consumer resolves the model's name
and settings through the model API with its own credentials. The
message row's model_id keeps the requested binding and can differ when
a request override is invalid and the turn falls back to the agent's
model; the event names the model that actually ran. The key is omitted
when no model is known. The quick-answer path is not changed.

The model name is left out on purpose. The completion event reaches
everyone who chats with the agent, including shared-agent users and
embed visitors, and an operator may not want to reveal which model
serves an agent; the provider-facing string can also be a deployment
override that the model API hides from non-admin callers. The message
history already returns the same ID to these users.
main
Ochan Kwon 2026-10-14 00:07:32 +09:00 committed by GitHub
parent 9238220867
commit 31c6055687
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 115 additions and 9 deletions

View File

@ -0,0 +1,38 @@
package agent
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
func captureCompletion(t *testing.T, engine *AgentEngine) event.AgentCompleteData {
t.Helper()
var got event.AgentCompleteData
engine.eventBus.On(event.EventAgentComplete, func(_ context.Context, evt event.Event) error {
got, _ = evt.Data.(event.AgentCompleteData)
return nil
})
engine.emitCompletionEvent(context.Background(), &types.AgentState{}, "session", "message", time.Now())
require.Equal(t, "message", got.MessageID, "the completion event was emitted")
return got
}
// The turn's usage comes only from calls through the engine's chat model, so
// the completion event names that model as the one the usage belongs to.
func TestCompletionEventNamesTheTurnsChatModel(t *testing.T) {
got := captureCompletion(t, newTestEngine(t, &mockChat{}))
require.Equal(t, "mock-id", got.ModelID)
}
func TestCompletionEventWithoutAChatModelNamesNone(t *testing.T) {
engine := newTestEngine(t, &mockChat{})
engine.chatModel = nil
require.Empty(t, captureCompletion(t, engine).ModelID)
}

View File

@ -158,19 +158,27 @@ func (e *AgentEngine) emitCompletionEvent(
knowledgeRefsInterface = append(knowledgeRefsInterface, ref)
}
data := event.AgentCompleteData{
FinalAnswer: state.FinalAnswer,
KnowledgeRefs: knowledgeRefsInterface,
AgentSteps: steps,
Usage: turnUsage(state),
TotalSteps: len(state.RoundSteps),
TotalDurationMs: time.Since(startTime).Milliseconds(),
MessageID: messageID, // Include message ID for proper message update
}
// The turn's usage is aggregated only from calls made through this chat
// model (each round and the final answer), so it is the model the usage
// belongs to. The message row keeps the requested binding, which can differ
// when a request override falls back to the agent's model.
if e.chatModel != nil {
data.ModelID = e.chatModel.GetModelID()
}
e.eventBus.Emit(ctx, event.Event{
ID: generateEventID("complete"),
Type: event.EventAgentComplete,
SessionID: sessionID,
Data: event.AgentCompleteData{
FinalAnswer: state.FinalAnswer,
KnowledgeRefs: knowledgeRefsInterface,
AgentSteps: steps,
Usage: turnUsage(state),
TotalSteps: len(state.RoundSteps),
TotalDurationMs: time.Since(startTime).Milliseconds(),
MessageID: messageID, // Include message ID for proper message update
},
Data: data,
})
logger.Infof(ctx, "Agent execution completed in %d rounds", state.CurrentRound)

View File

@ -142,6 +142,7 @@ type AgentCompleteData struct {
KnowledgeRefs []interface{} `json:"knowledge_refs,omitempty"` // []*types.SearchResult
AgentSteps interface{} `json:"agent_steps,omitempty"` // []types.AgentStep - detailed execution steps
Usage interface{} `json:"usage,omitempty"` // *types.TokenUsage - LLM token usage aggregated over the turn
ModelID string `json:"model_id,omitempty"` // Chat model whose calls produced Usage
TotalDurationMs int64 `json:"total_duration_ms"`
MessageID string `json:"message_id,omitempty"` // Assistant message ID
RequestID string `json:"request_id,omitempty"`

View File

@ -911,6 +911,10 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
if turnUsage != nil {
completeData["usage"] = turnUsage
}
// The chat model that produced the usage, so a consumer can price it.
if data.ModelID != "" {
completeData["model_id"] = data.ModelID
}
h.completionEvent = &interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeComplete,

View File

@ -0,0 +1,53 @@
package session
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
func publishedCompletion(t *testing.T, data event.AgentCompleteData) interfaces.StreamEvent {
t.Helper()
stream := &completionEventRecorder{}
message := &types.Message{ID: "m"}
handler := NewAgentStreamHandler(
context.Background(), "s", "m", "req", 1, time.Now(), message, stream, nil, nil, nil, nil,
)
require.NoError(t, handler.handleComplete(context.Background(), event.Event{Data: data}))
require.NoError(t, handler.publishCompletion(context.Background()))
last := stream.events[len(stream.events)-1]
require.Equal(t, types.ResponseTypeComplete, last.Type)
return last
}
// A relay that prices a turn's usage needs to know which model produced it.
// The model rides next to usage in the complete event's data, survives the
// stream manager's JSON round trip and reaches the response.
func TestCompletionEventCarriesTheTurnsChatModel(t *testing.T) {
last := publishedCompletion(t, event.AgentCompleteData{
MessageID: "m", ModelID: "model-1",
Usage: &types.TokenUsage{PromptTokens: 10, CompletionTokens: 2, TotalTokens: 12},
})
require.Equal(t, "model-1", last.Data["model_id"])
raw, err := json.Marshal(last)
require.NoError(t, err)
var restored interfaces.StreamEvent
require.NoError(t, json.Unmarshal(raw, &restored))
response := buildStreamResponse(restored, "req")
require.Equal(t, "model-1", response.Data["model_id"])
require.NotNil(t, response.Usage)
}
func TestCompletionEventOmitsAnUnknownModel(t *testing.T) {
last := publishedCompletion(t, event.AgentCompleteData{MessageID: "m"})
require.NotContains(t, last.Data, "model_id")
}

View File

@ -578,6 +578,8 @@ curl -X DELETE "$BASE/api/v1/artifacts?session_id=session-1&message_id=message-1
消息返回持久化的 usage,Agent 完成事件携带 turn_usage;包含本轮各用途模型调用聚合结果。工具调用自身并不都产生 Token,用量以提供商返回或后端已采集的记录为准。字段见[可观测性](../03-features/16-observability.md)。
智能体模式的完成事件在 `data.model_id` 中携带本轮实际运行的对话模型 ID(产生本轮用量的模型),可据此通过模型接口取得模型信息、按单价换算用量。消息记录中的 `model_id` 是请求时绑定的模型,请求指定的模型无效而回退到智能体模型时两者不同。快速问答的完成事件暂不携带该字段。
## 实现参考
路由注册:`internal/router/routes_chat.go` 的 `RegisterSessionRoutes`、`RegisterChatRoutes`、`RegisterMessageRoutes`(由 `internal/router/router.go` 调用)。Handler:`internal/handler/session/`(handler.go、qa.go、stream.go、title.go、temporary_document.go、fork.go、rewind.go、steer.go、artifact_*.go)、`internal/handler/message.go`、`internal/handler/message_suggestion.go`。