File size: 7,753 Bytes
8baf122 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | package jsonparser
import (
"strings"
"sync"
"time"
bifrost "github.com/maximhq/bifrost/core"
"github.com/maximhq/bifrost/core/schemas"
)
const (
PluginName = "streaming-json-parser"
)
type Usage string
const (
AllRequests Usage = "all_requests"
PerRequest Usage = "per_request"
)
// AccumulatedContent holds both the content and timestamp for a request
type AccumulatedContent struct {
Content *strings.Builder
Timestamp time.Time
}
// JsonParserPlugin provides JSON parsing capabilities for streaming responses
// It handles partial JSON chunks by accumulating them and making the accumulated content valid JSON
type JsonParserPlugin struct {
usage Usage
// State management for accumulating chunks
accumulatedContent map[string]*AccumulatedContent // requestID -> accumulated content with timestamp
mutex sync.RWMutex
// Cleanup configuration
cleanupInterval time.Duration
maxAge time.Duration
stopCleanup chan struct{}
stopOnce sync.Once
}
// PluginConfig holds configuration options for the JSON parser plugin
type PluginConfig struct {
Usage Usage
CleanupInterval time.Duration
MaxAge time.Duration
}
const (
EnableStreamingJSONParser schemas.BifrostContextKey = "enable-streaming-json-parser"
)
// Init creates a new JSON parser plugin instance with custom configuration
func Init(config PluginConfig) (*JsonParserPlugin, error) {
// Set defaults if not provided
if config.CleanupInterval <= 0 {
config.CleanupInterval = 5 * time.Minute
}
if config.MaxAge <= 0 {
config.MaxAge = 30 * time.Minute
}
if config.Usage == "" {
config.Usage = PerRequest
}
plugin := &JsonParserPlugin{
usage: config.Usage,
accumulatedContent: make(map[string]*AccumulatedContent),
cleanupInterval: config.CleanupInterval,
maxAge: config.MaxAge,
stopCleanup: make(chan struct{}),
}
// Start the cleanup goroutine
go plugin.startCleanupGoroutine()
return plugin, nil
}
// GetName returns the plugin name
func (p *JsonParserPlugin) GetName() string {
return PluginName
}
// HTTPTransportPreHook is not used for this plugin
func (p *JsonParserPlugin) HTTPTransportPreHook(ctx *schemas.BifrostContext, req *schemas.HTTPRequest) (*schemas.HTTPResponse, error) {
return nil, nil
}
// HTTPTransportPostHook is not used for this plugin
func (p *JsonParserPlugin) HTTPTransportPostHook(ctx *schemas.BifrostContext, req *schemas.HTTPRequest, resp *schemas.HTTPResponse) error {
return nil
}
// HTTPTransportStreamChunkHook passes through streaming chunks unchanged
func (p *JsonParserPlugin) HTTPTransportStreamChunkHook(ctx *schemas.BifrostContext, req *schemas.HTTPRequest, chunk *schemas.BifrostStreamChunk) (*schemas.BifrostStreamChunk, error) {
return chunk, nil
}
// PreLLMHook is not used for this plugin as we only process responses
// Parameters:
// - ctx: The Bifrost context
// - req: The Bifrost request
//
// Returns:
// - *schemas.BifrostRequest: The processed request
// - *schemas.LLMPluginShortCircuit: The plugin short circuit if the request is not allowed
// - error: Any error that occurred during processing
func (p *JsonParserPlugin) PreLLMHook(ctx *schemas.BifrostContext, req *schemas.BifrostRequest) (*schemas.BifrostRequest, *schemas.LLMPluginShortCircuit, error) {
return req, nil, nil
}
// PostLLMHook processes streaming responses by accumulating chunks and making accumulated content valid JSON
// Parameters:
// - ctx: The Bifrost context
// - result: The Bifrost response to be processed
// - err: The Bifrost error to be processed
//
// Returns:
// - *schemas.BifrostResponse: The processed response
// - *schemas.BifrostError: The processed error
// - error: Any error that occurred during processing
func (p *JsonParserPlugin) PostLLMHook(ctx *schemas.BifrostContext, result *schemas.BifrostResponse, err *schemas.BifrostError) (*schemas.BifrostResponse, *schemas.BifrostError, error) {
// If there's an error, don't process
if err != nil {
return result, err, nil
}
extraFields := result.GetExtraFields()
// Check if plugin should run based on usage type
if !p.shouldRun(ctx, extraFields.RequestType) {
return result, err, nil
}
// If no chat response, return as is
if result == nil || result.ChatResponse == nil {
return result, err, nil
}
// Get request ID for state management, if it's not set, return as is
requestID := p.getRequestID(ctx, result)
if requestID == "" {
return result, err, nil
}
// Create a deep copy of the result to avoid modifying the original pointer
// This ensures other plugins using the same pointer don't get corrupted data
resultCopy := p.deepCopyBifrostResponse(result)
if resultCopy == nil || resultCopy.ChatResponse == nil {
return result, err, nil
}
// Process only streaming choices to accumulate and fix partial JSON
if len(resultCopy.ChatResponse.Choices) > 0 {
for i := range resultCopy.ChatResponse.Choices {
choice := &resultCopy.ChatResponse.Choices[i]
// Handle only streaming response
if choice.ChatStreamResponseChoice != nil {
if choice.ChatStreamResponseChoice.Delta.Content != nil {
content := *choice.ChatStreamResponseChoice.Delta.Content
if content != "" {
// Accumulate the content
accumulated := p.accumulateContent(requestID, content)
// Process the accumulated content to make it valid JSON
fixedContent := p.parsePartialJSON(accumulated)
if !p.isValidJSON(fixedContent) {
err = &schemas.BifrostError{
Error: &schemas.ErrorField{
Message: "Invalid JSON in streaming response",
},
StreamControl: &schemas.StreamControl{
SkipStream: bifrost.Ptr(true),
},
}
return nil, err, nil
}
// Replace the delta content with the complete valid JSON
choice.ChatStreamResponseChoice.Delta.Content = &fixedContent
}
}
}
}
}
// If this is the final chunk, cleanup the accumulated content for this request
if streamEndIndicatorValue := ctx.Value(schemas.BifrostContextKeyStreamEndIndicator); streamEndIndicatorValue != nil {
isFinalChunk, ok := streamEndIndicatorValue.(bool)
if ok && isFinalChunk {
p.ClearRequestState(requestID)
}
}
// Return the modified copy instead of the original
return resultCopy, err, nil
}
// Cleanup performs plugin cleanup and clears accumulated content
func (p *JsonParserPlugin) Cleanup() error {
// Stop the cleanup goroutine
p.StopCleanup()
p.mutex.Lock()
defer p.mutex.Unlock()
// Clear accumulated content
p.accumulatedContent = make(map[string]*AccumulatedContent)
return nil
}
// ClearRequestState clears the accumulated content for a specific request
func (p *JsonParserPlugin) ClearRequestState(requestID string) {
p.mutex.Lock()
defer p.mutex.Unlock()
delete(p.accumulatedContent, requestID)
}
// CLEANUP METHODS
// startCleanupGoroutine starts a goroutine that periodically cleans up old accumulated content
func (p *JsonParserPlugin) startCleanupGoroutine() {
ticker := time.NewTicker(p.cleanupInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
p.cleanupOldEntries()
case <-p.stopCleanup:
return
}
}
}
// cleanupOldEntries removes accumulated content entries that are older than maxAge
func (p *JsonParserPlugin) cleanupOldEntries() {
p.mutex.Lock()
defer p.mutex.Unlock()
now := time.Now()
cutoff := now.Add(-p.maxAge)
for requestID, content := range p.accumulatedContent {
if content.Timestamp.Before(cutoff) {
delete(p.accumulatedContent, requestID)
}
}
}
// StopCleanup stops the cleanup goroutine
func (p *JsonParserPlugin) StopCleanup() {
p.stopOnce.Do(func() {
close(p.stopCleanup)
})
}
|