File size: 8,911 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package jsonparser

import (
	"encoding/json"
	"strings"
	"time"

	"github.com/maximhq/bifrost/core/schemas"
)

// getRequestID extracts a unique identifier for the request to maintain state
func (p *JsonParserPlugin) getRequestID(ctx *schemas.BifrostContext, result *schemas.BifrostResponse) string {

	// Try to get from result
	if result != nil && result.ChatResponse != nil && result.ChatResponse.ID != "" {
		return result.ChatResponse.ID
	}

	// Try to get from context if not available in result
	if ctx != nil {
		if requestID, ok := ctx.Value(schemas.BifrostContextKeyRequestID).(string); ok && requestID != "" {
			return requestID
		}
	}

	return ""
}

// shouldRun determines if the plugin should process the request based on usage type
func (p *JsonParserPlugin) shouldRun(ctx *schemas.BifrostContext, requestType schemas.RequestType) bool {
	// Run only for chat completion stream requests
	if requestType != schemas.ChatCompletionStreamRequest {
		return false
	}

	switch p.usage {
	case AllRequests:
		return true
	case PerRequest:
		// Check if the context contains the plugin-specific key
		if ctx != nil {
			if value, ok := ctx.Value(EnableStreamingJSONParser).(bool); ok {
				return value
			}
		}
		return false
	default:
		return false
	}
}

// accumulateContent adds new content to the accumulated content for a specific request
func (p *JsonParserPlugin) accumulateContent(requestID, newContent string) string {
	p.mutex.Lock()
	defer p.mutex.Unlock()

	// Get existing accumulated content
	existing := p.accumulatedContent[requestID]

	if existing != nil {
		// Append to existing builder
		existing.Content.WriteString(newContent)
		return existing.Content.String()
	} else {
		// Create new builder
		builder := &strings.Builder{}
		builder.WriteString(newContent)
		p.accumulatedContent[requestID] = &AccumulatedContent{
			Content:   builder,
			Timestamp: time.Now(),
		}
		return builder.String()
	}
}

// parsePartialJSON parses a JSON string that may be missing closing braces
func (p *JsonParserPlugin) parsePartialJSON(s string) string {
	// Trim whitespace
	s = strings.TrimSpace(s)
	if s == "" {
		return "{}"
	}

	// Quick check: if it starts with { or [, it might be JSON
	if s[0] != '{' && s[0] != '[' {
		return s
	}

	// First, try to parse the string as-is (fast path)
	if p.isValidJSON(s) {
		return s
	}

	// Use a more efficient approach: build the completion directly
	return p.completeJSON(s)
}

// completeJSON completes partial JSON with O(n) time complexity
func (p *JsonParserPlugin) completeJSON(s string) string {
	// Pre-allocate buffer with estimated capacity
	capacity := len(s) + 10 // Estimate max 10 closing characters needed
	result := make([]byte, 0, capacity)

	var stack []byte
	inString := false
	escaped := false

	// Process the string once
	for i := 0; i < len(s); i++ {
		char := s[i]
		result = append(result, char)

		if escaped {
			escaped = false
			continue
		}

		if char == '\\' {
			escaped = true
			continue
		}

		if char == '"' {
			inString = !inString
			continue
		}

		if inString {
			continue
		}

		switch char {
		case '{', '[':
			if char == '{' {
				stack = append(stack, '}')
			} else {
				stack = append(stack, ']')
			}
		case '}', ']':
			if len(stack) > 0 && stack[len(stack)-1] == char {
				stack = stack[:len(stack)-1]
			}
		}
	}

	// Close any unclosed strings
	if inString {
		if escaped {
			// Remove the trailing backslash
			if len(result) > 0 {
				result = result[:len(result)-1]
			}
		}
		result = append(result, '"')
	}

	// Add closing characters in reverse order
	for i := len(stack) - 1; i >= 0; i-- {
		result = append(result, stack[i])
	}

	// Validate the result
	if p.isValidJSON(string(result)) {
		return string(result)
	}

	// If still invalid, try progressive truncation (but more efficiently)
	return p.progressiveTruncation(s, result)
}

// progressiveTruncation efficiently tries different truncation points
func (p *JsonParserPlugin) progressiveTruncation(original string, completed []byte) string {
	// Try removing characters from the end until we get valid JSON
	// Use binary search for better performance
	left, right := 0, len(completed)

	for left < right {
		mid := (left + right) / 2
		candidate := completed[:mid]

		if p.isValidJSON(string(candidate)) {
			left = mid + 1
		} else {
			right = mid
		}
	}

	// Try the best candidate
	if left > 0 && p.isValidJSON(string(completed[:left-1])) {
		return string(completed[:left-1])
	}

	// Fallback to original
	return original
}

// isValidJSON checks if a string is valid JSON
func (p *JsonParserPlugin) isValidJSON(s string) bool {
	// Trim whitespace
	s = strings.TrimSpace(s)

	// Empty string after trimming is not valid JSON
	if s == "" {
		return false
	}

	return json.Valid([]byte(s))
}

// DEEP COPY METHODS

// deepCopyBifrostResponse creates a deep copy of BifrostResponse to avoid modifying the original
func (p *JsonParserPlugin) deepCopyBifrostResponse(original *schemas.BifrostResponse) *schemas.BifrostResponse {
	if original == nil {
		return nil
	}

	// Create a new BifrostResponse
	result := &schemas.BifrostResponse{}

	// Copy ChatResponse if it exists (this is what we're interested in for the JSON parser)
	if original.ChatResponse != nil {
		result.ChatResponse = p.deepCopyBifrostChatResponse(original.ChatResponse)
	}

	// Copy other response types if they exist (shallow copy since we don't modify them)
	result.TextCompletionResponse = original.TextCompletionResponse
	result.ResponsesResponse = original.ResponsesResponse
	result.ResponsesStreamResponse = original.ResponsesStreamResponse
	result.EmbeddingResponse = original.EmbeddingResponse
	result.SpeechResponse = original.SpeechResponse
	result.SpeechStreamResponse = original.SpeechStreamResponse
	result.TranscriptionResponse = original.TranscriptionResponse
	result.TranscriptionStreamResponse = original.TranscriptionStreamResponse

	return result
}

// deepCopyBifrostChatResponse creates a deep copy of BifrostChatResponse
func (p *JsonParserPlugin) deepCopyBifrostChatResponse(original *schemas.BifrostChatResponse) *schemas.BifrostChatResponse {
	if original == nil {
		return nil
	}

	result := &schemas.BifrostChatResponse{
		ID:                original.ID,
		Created:           original.Created,
		Model:             original.Model,
		Object:            original.Object,
		ServiceTier:       original.ServiceTier,
		SystemFingerprint: original.SystemFingerprint,
		Usage:             original.Usage,       // Shallow copy - usage shouldn't be modified
		ExtraFields:       original.ExtraFields, // Shallow copy
	}

	// Deep copy Choices slice
	if original.Choices != nil {
		result.Choices = make([]schemas.BifrostResponseChoice, len(original.Choices))
		for i, choice := range original.Choices {
			result.Choices[i] = p.deepCopyBifrostResponseChoice(choice)
		}
	}

	return result
}

// deepCopyBifrostResponseChoice creates a deep copy of BifrostResponseChoice
func (p *JsonParserPlugin) deepCopyBifrostResponseChoice(original schemas.BifrostResponseChoice) schemas.BifrostResponseChoice {
	result := schemas.BifrostResponseChoice{
		Index:        original.Index,
		FinishReason: original.FinishReason,
		LogProbs:     original.LogProbs,
	}

	// Deep copy ChatStreamResponseChoice if it exists (this is what we modify)
	if original.ChatStreamResponseChoice != nil {
		result.ChatStreamResponseChoice = p.deepCopyChatStreamResponseChoice(original.ChatStreamResponseChoice)
	}

	// Shallow copy other choice types since we don't modify them
	result.ChatNonStreamResponseChoice = original.ChatNonStreamResponseChoice
	result.TextCompletionResponseChoice = original.TextCompletionResponseChoice

	return result
}

// deepCopyChatStreamResponseChoice creates a deep copy of ChatStreamResponseChoice
func (p *JsonParserPlugin) deepCopyChatStreamResponseChoice(original *schemas.ChatStreamResponseChoice) *schemas.ChatStreamResponseChoice {
	if original == nil {
		return nil
	}

	result := &schemas.ChatStreamResponseChoice{}

	// Deep copy Delta pointer if it exists
	if original.Delta != nil {
		result.Delta = p.deepCopyChatStreamResponseChoiceDelta(original.Delta)
	}

	return result
}

// deepCopyChatStreamResponseChoiceDelta creates a deep copy of ChatStreamResponseChoiceDelta
func (p *JsonParserPlugin) deepCopyChatStreamResponseChoiceDelta(original *schemas.ChatStreamResponseChoiceDelta) *schemas.ChatStreamResponseChoiceDelta {
	if original == nil {
		return nil
	}

	result := &schemas.ChatStreamResponseChoiceDelta{
		Role:      original.Role,
		Reasoning: original.Reasoning, // Shallow copy
		Refusal:   original.Refusal,   // Shallow copy
		ToolCalls: original.ToolCalls, // Shallow copy - we don't modify tool calls
	}

	// Deep copy Content pointer if it exists (this is what we modify)
	if original.Content != nil {
		contentCopy := *original.Content
		result.Content = &contentCopy
	}

	return result
}