refactor: Implement event-driven streaming and enhance session management

- Removed the StreamEvent accumulation logic, transitioning to an append-only model for event streaming.
- Updated StreamManager interface to support appending events and retrieving events with offsets.
- Enhanced session handling to support real-time event emission through an EventBus, improving responsiveness.
- Refactored chat pipeline components to utilize the new event-driven architecture, ensuring seamless integration of agent responses and knowledge references.
- Improved frontend components to handle the new event structure, ensuring accurate rendering of agent interactions and responses.
This commit is contained in:
wizardchen
2025-11-07 22:41:41 +08:00
parent def8e4b426
commit 326a61696a
19 changed files with 1144 additions and 1496 deletions
@@ -3,10 +3,13 @@ package chatpipline
import (
"context"
"errors"
"fmt"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// PluginChatCompletionStream implements streaming chat completion functionality
@@ -49,7 +52,16 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
logger.Info(ctx, "Preparing chat messages")
chatMessages := prepareMessagesWithHistory(chatManage)
// Initiate streaming chat model call
// EventBus is required for event-driven streaming
if chatManage.EventBus == nil {
logger.Error(ctx, "EventBus is required but not available")
return ErrModelCall.WithError(errors.New("EventBus is required for streaming"))
}
eventBus := chatManage.EventBus
logger.Info(ctx, "EventBus detected, enabling event-driven streaming mode")
// Initiate streaming chat model call with independent context
logger.Info(ctx, "Calling chat stream model")
responseChan, err := chatModel.ChatStream(ctx, chatMessages, opt)
if err != nil {
@@ -62,6 +74,49 @@ func (p *PluginChatCompletionStream) OnEvent(ctx context.Context,
}
logger.Info(ctx, "Chat stream initiated successfully")
chatManage.ResponseChan = responseChan
// Start goroutine to consume channel and emit events directly
go func() {
answerID := fmt.Sprintf("%s-answer", uuid.New().String()[:8])
var finalContent string
for response := range responseChan {
// Emit event for each answer chunk
if response.ResponseType == types.ResponseTypeAnswer {
finalContent += response.Content
if err := eventBus.Emit(ctx, types.Event{
ID: answerID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{
Content: response.Content,
Done: response.Done,
},
}); err != nil {
logger.Errorf(ctx, "Failed to emit answer event: %v", err)
}
}
}
logger.Info(ctx, "Chat stream completed, emitting completion event")
// Emit completion event when stream finishes
// This allows other components to detect stream completion
if err := eventBus.Emit(ctx, types.Event{
ID: fmt.Sprintf("%s-complete", uuid.New().String()[:8]),
Type: types.EventType(event.EventAgentComplete),
SessionID: chatManage.SessionID,
Data: event.AgentCompleteData{
SessionID: chatManage.SessionID,
MessageID: chatManage.MessageID,
FinalAnswer: finalContent,
},
}); err != nil {
logger.Errorf(ctx, "Failed to emit completion event: %v", err)
}
logger.Info(ctx, "Chat stream completed and completion event emitted")
}()
return next()
}
@@ -138,24 +138,3 @@ func (p *PluginError) WithError(err error) *PluginError {
pp.Err = err
return pp
}
// NewFallbackChan creates a channel with a single fallback response
func NewFallbackChan(ctx context.Context, fallbackResponse string) <-chan types.StreamResponse {
fallabackChan := make(chan types.StreamResponse)
go func() {
fallabackChan <- NewFallback(ctx, fallbackResponse)
close(fallabackChan)
}()
return fallabackChan
}
// NewFallback creates a fallback stream response with the given content
func NewFallback(ctx context.Context, fallbackResponse string) types.StreamResponse {
requestID := ctx.Value(types.RequestIDContextKey).(string)
return types.StreamResponse{
ID: requestID,
ResponseType: types.ResponseTypeAnswer,
Content: fallbackResponse,
Done: true,
}
}
@@ -2,10 +2,14 @@ package chatpipline
import (
"context"
"errors"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/google/uuid"
)
// PluginStreamFilter implements stream filtering functionality for chat pipeline
@@ -28,57 +32,93 @@ func (p *PluginStreamFilter) OnEvent(ctx context.Context,
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Starting stream filter")
logger.Info(ctx, "Creating new stream channel")
// Create new stream channel and replace the original one
oldStream := chatManage.ResponseChan
newStream := make(chan types.StreamResponse)
chatManage.ResponseChan = newStream
// EventBus is required
if chatManage.EventBus == nil {
logger.Error(ctx, "EventBus is required but not available")
return ErrModelCall.WithError(errors.New("EventBus is required for stream filtering"))
}
eventBus := chatManage.EventBus
// Initialize response builder and check if no-match prefix filtering is needed
responseBuilder := &strings.Builder{}
// Check if no-match prefix filtering is needed
matchNoMatchBuilderPrefix := chatManage.SummaryConfig.NoMatchPrefix != ""
if matchNoMatchBuilderPrefix {
logger.Infof(ctx, "Using no match prefix filter: %s", chatManage.SummaryConfig.NoMatchPrefix)
// Create an event interceptor for prefix filtering
return p.filterEventsWithPrefix(ctx, chatManage, eventBus, next)
}
// Start goroutine to filter the stream
go func() {
logger.Info(ctx, "Starting stream filter goroutine")
for resp := range oldStream {
// Accumulate answer content
if resp.ResponseType == types.ResponseTypeAnswer {
responseBuilder.WriteString(resp.Content)
}
// Skip filtering if no prefix matching is required
if !matchNoMatchBuilderPrefix {
newStream <- resp
continue
}
// Check if content matches the no-match prefix
if !strings.HasPrefix(chatManage.SummaryConfig.NoMatchPrefix, responseBuilder.String()) {
resp.Content = responseBuilder.String()
newStream <- resp
logger.Info(
ctx, "Content does not match no-match prefix, passing through, content: ",
responseBuilder.String(),
)
matchNoMatchBuilderPrefix = false
}
}
// Handle NO_MATCH case when stream ends
if matchNoMatchBuilderPrefix {
logger.Info(ctx, "Content matches no-match prefix, using fallback response")
newStream <- NewFallback(ctx, chatManage.FallbackResponse)
}
logger.Info(ctx, "Stream filter completed, closing new stream")
close(newStream)
}()
logger.Info(ctx, "Stream filter initialized")
// No filtering needed, just pass through
logger.Info(ctx, "No prefix filtering required, passing through")
return next()
}
// filterEventsWithPrefix intercepts events, checks for NoMatchPrefix, and re-emits filtered events
func (p *PluginStreamFilter) filterEventsWithPrefix(
ctx context.Context,
chatManage *types.ChatManage,
originalEventBus types.EventBusInterface,
next func() *PluginError,
) *PluginError {
logger.Info(ctx, "Setting up event-based stream filtering with NoMatchPrefix")
// Create a temporary EventBus to intercept events
tempEventBus := event.NewEventBus()
chatManage.EventBus = tempEventBus.AsEventBusInterface()
responseBuilder := &strings.Builder{}
matchFound := false
// Subscribe to answer events from temp bus
tempEventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentFinalAnswerData)
if !ok {
return nil
}
responseBuilder.WriteString(data.Content)
// Check if content does NOT match the no-match prefix (meaning it's valid content)
if !strings.HasPrefix(chatManage.SummaryConfig.NoMatchPrefix, responseBuilder.String()) {
logger.Infof(ctx, "Content does not match no-match prefix, emitting valid content: %s", responseBuilder.String())
// Emit the accumulated content as valid answer
originalEventBus.Emit(ctx, types.Event{
ID: evt.ID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{
Content: responseBuilder.String(),
Done: data.Done,
},
})
matchFound = true
}
return nil
})
// Call next to trigger pipeline stages that will emit to tempEventBus
err := next()
// After pipeline completes, check if we need fallback
if !matchFound && responseBuilder.Len() > 0 {
logger.Info(ctx, "Content matches no-match prefix, emitting fallback response")
fallbackID := fmt.Sprintf("%s-fallback", uuid.New().String()[:8])
originalEventBus.Emit(ctx, types.Event{
ID: fallbackID,
Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{
Content: chatManage.FallbackResponse,
Done: true,
},
})
}
// Restore original EventBus
chatManage.EventBus = originalEventBus
return err
}
@@ -6,6 +6,8 @@ import (
"strings"
"time"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/tracing"
"github.com/Tencent/WeKnora/internal/types"
"go.opentelemetry.io/otel/attribute"
@@ -187,28 +189,37 @@ func (p *PluginTracing) ChatCompletionStream(ctx context.Context,
)
responseBuilder := &strings.Builder{}
oldStream := chatManage.ResponseChan
newStream := make(chan types.StreamResponse)
chatManage.ResponseChan = newStream
go func(ctx context.Context) {
for resp := range oldStream {
if resp.ResponseType == types.ResponseTypeAnswer {
responseBuilder.WriteString(resp.Content)
// EventBus is required
if chatManage.EventBus == nil {
logger.Warn(ctx, "Tracing: EventBus not available, skipping metrics collection")
return next()
}
eventBus := chatManage.EventBus
// Subscribe to events and collect metrics
logger.Info(ctx, "Tracing: Subscribing to answer events for metrics collection")
eventBus.On(types.EventType(event.EventAgentFinalAnswer), func(ctx context.Context, evt types.Event) error {
data, ok := evt.Data.(event.AgentFinalAnswerData)
if ok {
responseBuilder.WriteString(data.Content)
// If this is the final chunk, record metrics
if data.Done {
elapsedMS := time.Since(startTime).Milliseconds()
span.SetAttributes(
attribute.Bool("chat_completion_success", true),
attribute.Int64("response_time_ms", elapsedMS),
attribute.String("chat_response", responseBuilder.String()),
attribute.Int("final_response_length", responseBuilder.Len()),
attribute.Float64("tokens_per_second", float64(responseBuilder.Len())/float64(elapsedMS)*1000),
)
span.End()
}
newStream <- resp
}
elapsedMS := time.Since(startTime).Milliseconds()
span.SetAttributes(
attribute.Bool("chat_completion_success", true),
attribute.Int64("response_time_ms", elapsedMS),
attribute.String("chat_response", responseBuilder.String()),
attribute.Int("final_response_length", responseBuilder.Len()),
attribute.Float64("tokens_per_second", float64(responseBuilder.Len())/float64(elapsedMS)*1000),
)
span.End()
close(newStream)
}(ctx)
return nil
})
return next()
}