feat(agent): enhance token management and context handling in AgentEngine

- Added token usage tracking to the AgentEngine, allowing for better estimation of current context token counts.
- Implemented a new method to estimate current tokens based on previous usage and newly appended messages, improving context management.
- Updated context window management to utilize estimated token counts for more efficient message consolidation.
- Enhanced streaming methods to include token usage information, providing better insights into LLM interactions.
- Refactored the token estimator to support BPE tokenization, ensuring accurate token counts for messages.
- Added unit tests to validate new token estimation and context management functionalities.
This commit is contained in:
wizardchen
2026-03-22 23:15:33 +08:00
committed by lyingbug
parent 0d4ceb6c96
commit 0bb1a581de
16 changed files with 247 additions and 239 deletions
+24 -5
View File
@@ -152,6 +152,10 @@ func (c *RemoteAPIChat) BuildChatCompletionRequest(messages []Message, opts *Cha
Stream: isStream,
}
if isStream {
req.StreamOptions = &openai.StreamOptions{IncludeUsage: true}
}
if opts != nil {
if opts.Temperature > 0 {
req.Temperature = float32(opts.Temperature)
@@ -316,11 +320,7 @@ func (c *RemoteAPIChat) parseCompletionResponse(resp *openai.ChatCompletionRespo
response := &types.ChatResponse{
Content: content,
FinishReason: string(choice.FinishReason),
Usage: struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}{
Usage: types.TokenUsage{
PromptTokens: resp.Usage.PromptTokens,
CompletionTokens: resp.Usage.CompletionTokens,
TotalTokens: resp.Usage.TotalTokens,
@@ -465,6 +465,7 @@ func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCo
Content: "",
Done: true,
ToolCalls: state.buildOrderedToolCalls(),
Usage: state.usage,
}
} else {
streamChan <- types.StreamResponse{
@@ -476,6 +477,14 @@ func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCo
return
}
if response.Usage != nil {
state.usage = &types.TokenUsage{
PromptTokens: response.Usage.PromptTokens,
CompletionTokens: response.Usage.CompletionTokens,
TotalTokens: response.Usage.TotalTokens,
}
}
if len(response.Choices) > 0 {
c.processStreamDelta(ctx, &response.Choices[0], state, streamChan, response.Choices[0].Delta.ReasoningContent)
}
@@ -514,6 +523,7 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res
Content: "",
Done: true,
ToolCalls: state.buildOrderedToolCalls(),
Usage: state.usage,
}
return
}
@@ -540,6 +550,14 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res
continue
}
if streamResp.Usage != nil {
state.usage = &types.TokenUsage{
PromptTokens: streamResp.Usage.PromptTokens,
CompletionTokens: streamResp.Usage.CompletionTokens,
TotalTokens: streamResp.Usage.TotalTokens,
}
}
if len(streamResp.Choices) > 0 {
choice := streamResp.Choices[0]
// 统一获取逻辑(支持标准和 vLLM 两种路径)
@@ -566,6 +584,7 @@ type streamState struct {
nameNotified map[int]bool
hasThinking bool
fieldExtractors map[int]*jsonFieldExtractor // per tool-call-index extractors for streaming field extraction
usage *types.TokenUsage // captured from the final stream chunk when include_usage is enabled
}
func newStreamState() *streamState {