Spaces:
Paused
Paused
Commit ·
0a33ddd
1
Parent(s): 04c79ee
bug fixes
Browse filesFiles changed (2)
- app/api_helpers.py+84-28
- app/openai_handler.py+49-21
33 unmodified lines3435363738395 unmodified lines4546474849505152534 unmodified lines5859606162636465666768694 unmodified lines74757677787980818283848586878889909111 unmodified lines10310410510610710810911011111211311411511611711811933 unmodified linesself.tag_buffer = ""self.inside_tag = Falseself.reasoning_buffer = ""def process_chunk(self, content: str) -> tuple[str, str]:"""5 unmodified linesReturns:A tuple of:- processed_content: Content with reasoning tags removed- current_reasoning: Complete reasoning text if a closing tag was found"""# Add new content to bufferself.tag_buffer += contentprocessed_content = ""4 unmodified lines# Look for opening tagopen_pos = self.tag_buffer.find(self.open_tag)if open_pos == -1:# No opening tag foundif len(self.tag_buffer) >= len(self.open_tag):# Safe to output all but the last few chars (in case tag is split)safe_length = len(self.tag_buffer) - len(self.open_tag) + 1processed_content += self.tag_buffer[:safe_length]self.tag_buffer = self.tag_buffer[safe_length:]breakelse:# Found opening tag4 unmodified lines# Inside tag, look for closing tagclose_pos = self.tag_buffer.find(self.close_tag)if close_pos == -1:# No closing tag yetif len(self.tag_buffer) >= len(self.close_tag):# Safe to add to reasoning buffersafe_length = len(self.tag_buffer) - len(self.close_tag) + 1self.reasoning_buffer += self.tag_buffer[:safe_length]self.tag_buffer = self.tag_buffer[safe_length:]breakelse:# Found closing tagself.reasoning_buffer += self.tag_buffer[:close_pos]current_reasoning = self.reasoning_bufferself.reasoning_buffer = ""self.tag_buffer = self.tag_buffer[close_pos + len(self.close_tag):]self.inside_tag = False11 unmodified linesremaining_content = ""remaining_reasoning = ""if self.tag_buffer and not self.inside_tag:# If we have buffered content and we're not inside a tag,# it's safe to output all of itremaining_content = self.tag_bufferself.tag_buffer = ""elif self.inside_tag:# If we're inside a tag when the stream ends, we have an unclosed tag# Return the partial content as regular content (including the opening tag)remaining_content = f"<{self.tag_name}>{self.reasoning_buffer}{self.tag_buffer}"self.reasoning_buffer = ""self.tag_buffer = ""self.inside_tag = Falsereturn remaining_content, remaining_reasoning33 unmodified lines343536373839405 unmodified lines46474849505152535455565758594 unmodified lines6465666768697071727374757677787980818283848586878889904 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313411 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716816917017117217317417533 unmodified linesself.tag_buffer = ""self.inside_tag = Falseself.reasoning_buffer = ""self.partial_tag_buffer = "" # Buffer for potential partial tagsdef process_chunk(self, content: str) -> tuple[str, str]:"""5 unmodified linesReturns:A tuple of:- processed_content: Content with reasoning tags removed- current_reasoning: Reasoning text found in this chunk (partial or complete)"""# Add new content to buffer, but also handle any partial tag from beforeif self.partial_tag_buffer:# We had a partial tag from the previous chunkcontent = self.partial_tag_buffer + contentself.partial_tag_buffer = ""self.tag_buffer += contentprocessed_content = ""4 unmodified lines# Look for opening tagopen_pos = self.tag_buffer.find(self.open_tag)if open_pos == -1:# No complete opening tag found# Check if we might have a partial tag at the endpartial_match = Falsefor i in range(1, min(len(self.open_tag), len(self.tag_buffer) + 1)):if self.tag_buffer[-i:] == self.open_tag[:i]:partial_match = True# Output everything except the potential partial tagif len(self.tag_buffer) > i:processed_content += self.tag_buffer[:-i]self.partial_tag_buffer = self.tag_buffer[-i:]self.tag_buffer = ""else:# Entire buffer is partial tagself.partial_tag_buffer = self.tag_bufferself.tag_buffer = ""breakif not partial_match:# No partial tag, output everythingprocessed_content += self.tag_bufferself.tag_buffer = ""breakelse:# Found opening tag4 unmodified lines# Inside tag, look for closing tagclose_pos = self.tag_buffer.find(self.close_tag)if close_pos == -1:# No complete closing tag yet# Check for partial closing tagpartial_match = Falsefor i in range(1, min(len(self.close_tag), len(self.tag_buffer) + 1)):if self.tag_buffer[-i:] == self.close_tag[:i]:partial_match = True# Add everything except potential partial tag to reasoningif len(self.tag_buffer) > i:new_reasoning = self.tag_buffer[:-i]self.reasoning_buffer += new_reasoningif new_reasoning: # Stream reasoning as it arrivescurrent_reasoning = new_reasoningself.partial_tag_buffer = self.tag_buffer[-i:]self.tag_buffer = ""else:# Entire buffer is partial tagself.partial_tag_buffer = self.tag_bufferself.tag_buffer = ""breakif not partial_match:# No partial tag, add all to reasoning and stream itif self.tag_buffer:self.reasoning_buffer += self.tag_buffercurrent_reasoning = self.tag_bufferself.tag_buffer = ""breakelse:# Found closing tagfinal_reasoning_chunk = self.tag_buffer[:close_pos]self.reasoning_buffer += final_reasoning_chunkif final_reasoning_chunk: # Include the last chunk of reasoningcurrent_reasoning = final_reasoning_chunkself.reasoning_buffer = "" # Clear buffer after complete tagself.tag_buffer = self.tag_buffer[close_pos + len(self.close_tag):]self.inside_tag = False11 unmodified linesremaining_content = ""remaining_reasoning = ""# First handle any partial tag bufferif self.partial_tag_buffer:# The partial tag wasn't completed, so treat it as regular contentremaining_content += self.partial_tag_bufferself.partial_tag_buffer = ""if not self.inside_tag:# If we're not inside a tag, output any remaining bufferif self.tag_buffer:remaining_content += self.tag_bufferself.tag_buffer = ""else:# If we're inside a tag when stream ends, we have incomplete reasoning# First, yield any reasoning we've accumulatedif self.reasoning_buffer:remaining_reasoning = self.reasoning_bufferself.reasoning_buffer = ""# Then output the remaining buffer as content (it's an incomplete tag)if self.tag_buffer:# Don't include the opening tag in output - just the buffer contentremaining_content += self.tag_bufferself.tag_buffer = ""self.inside_tag = Falsereturn remaining_content, remaining_reasoning
120 unmodified lines12112212312412512618 unmodified lines1451461471481491501511521531541551561571581591601611621631648 unmodified lines173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207120 unmodified lines# Create processor for tag-based extraction across chunksreasoning_processor = StreamingReasoningProcessor(VERTEX_REASONING_TAG)chunk_count = 0async for chunk in stream_response:chunk_count += 118 unmodified linesif processed_content or current_reasoning:print(f"DEBUG: Chunk {chunk_count} - Processed content: '{processed_content}', Reasoning: '{current_reasoning[:50]}...' if len(current_reasoning) > 50 else '{current_reasoning}'")# Update delta with processed contentif current_reasoning:delta['reasoning_content'] = current_reasoningif processed_content:delta['content'] = processed_contentelif 'content' in delta:del delta['content']yield f"data: {json.dumps(chunk_as_dict)}\n\n"except Exception as chunk_error:error_msg = f"Error processing OpenAI chunk for {request.model}: {str(chunk_error)}"print(f"ERROR: {error_msg}")if len(error_msg) > 1024:error_msg = error_msg[:1024] + "..."error_response = create_openai_error_response(500, error_msg, "server_error")yield f"data: {json.dumps(error_response)}\n\n"8 unmodified lines# Flush any remaining buffered contentremaining_content, remaining_reasoning = reasoning_processor.flush_remaining()if remaining_content:print(f"DEBUG: Flushing remaining content: '{remaining_content}'")final_chunk = {"id": f"chatcmpl-{int(time.time())}","object": "chat.completion.chunk","created": int(time.time()),"model": request.model,"choices": [{"index": 0, "delta": {"content": remaining_content}, "finish_reason": None}]}yield f"data: {json.dumps(final_chunk)}\n\n"# Send a proper finish reason chunkfinish_chunk = {"id": f"chatcmpl-{int(time.time())}","object": "chat.completion.chunk","created": int(time.time()),"model": request.model,"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}yield f"data: {json.dumps(finish_chunk)}\n\n"# Note: remaining_reasoning is not used here since incomplete reasoning# is treated as regular content when tags are unclosedyield "data: [DONE]\n\n"except Exception as stream_error:error_msg = str(stream_error)if len(error_msg) > 1024:error_msg = error_msg[:1024] + "..."error_msg_full = f"Error during OpenAI streaming for {request.model}: {error_msg}"print(f"ERROR: {error_msg_full}")120 unmodified lines12112212312412512612718 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801818 unmodified lines190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235120 unmodified lines# Create processor for tag-based extraction across chunksreasoning_processor = StreamingReasoningProcessor(VERTEX_REASONING_TAG)chunk_count = 0has_sent_content = Falseasync for chunk in stream_response:chunk_count += 118 unmodified linesif processed_content or current_reasoning:print(f"DEBUG: Chunk {chunk_count} - Processed content: '{processed_content}', Reasoning: '{current_reasoning[:50]}...' if len(current_reasoning) > 50 else '{current_reasoning}'")# Send chunks for both reasoning and content as they arrivechunks_to_send = []# If we have reasoning content, send itif current_reasoning:reasoning_chunk = chunk_as_dict.copy()reasoning_chunk['choices'][0]['delta'] = {'reasoning_content': current_reasoning}chunks_to_send.append(reasoning_chunk)# If we have regular content, send itif processed_content:content_chunk = chunk_as_dict.copy()content_chunk['choices'][0]['delta'] = {'content': processed_content}chunks_to_send.append(content_chunk)has_sent_content = True# Send all chunksfor chunk_to_send in chunks_to_send:yield f"data: {json.dumps(chunk_to_send)}\n\n"else:# Still yield the chunk even if no content (could have other delta fields)yield f"data: {json.dumps(chunk_as_dict)}\n\n"else:# Yield chunks without choices too (they might contain metadata)yield f"data: {json.dumps(chunk_as_dict)}\n\n"except Exception as chunk_error:error_msg = f"Error processing OpenAI chunk for {request.model}: {str(chunk_error)}"print(f"ERROR: {error_msg}")if len(error_msg) > 1024:error_msg = error_msg[:1024] + "..."error_response = create_openai_error_response(500, error_msg, "server_error")yield f"data: {json.dumps(error_response)}\n\n"8 unmodified lines# Flush any remaining buffered contentremaining_content, remaining_reasoning = reasoning_processor.flush_remaining()# Send any remaining reasoning firstif remaining_reasoning:print(f"DEBUG: Flushing remaining reasoning: '{remaining_reasoning[:50]}...' if len(remaining_reasoning) > 50 else '{remaining_reasoning}'")reasoning_chunk = {"id": f"chatcmpl-{int(time.time())}","object": "chat.completion.chunk","created": int(time.time()),"model": request.model,"choices": [{"index": 0, "delta": {"reasoning_content": remaining_reasoning}, "finish_reason": None}]}yield f"data: {json.dumps(reasoning_chunk)}\n\n"# Send any remaining contentif remaining_content:print(f"DEBUG: Flushing remaining content: '{remaining_content}'")final_chunk = {"id": f"chatcmpl-{int(time.time())}","object": "chat.completion.chunk","created": int(time.time()),"model": request.model,"choices": [{"index": 0, "delta": {"content": remaining_content}, "finish_reason": None}]}yield f"data: {json.dumps(final_chunk)}\n\n"has_sent_content = True# Always send a finish reason chunkfinish_chunk = {"id": f"chatcmpl-{int(time.time())}","object": "chat.completion.chunk","created": int(time.time()),"model": request.model,"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}yield f"data: {json.dumps(finish_chunk)}\n\n"yield "data: [DONE]\n\n"except Exception as stream_error:error_msg = str(stream_error)if len(error_msg) > 1024:error_msg = error_msg[:1024] + "..."error_msg_full = f"Error during OpenAI streaming for {request.model}: {error_msg}"print(f"ERROR: {error_msg_full}")
app/api_helpers.py+84-28
app/openai_handler.py+49-21