spring-projects / spring-ai

An Application Framework for AI Engineering
https://docs.spring.io/spring-ai/reference/index.html
Apache License 2.0
3.32k stars 850 forks source link

Code Duplication in Event Type Checks #1764

Open cowboysj opened 2 days ago

cowboysj commented 2 days ago

Description

The methods isToolUseStart and isToolUseFinish in the StreamHelper class contain repeated logic for checking if a StreamEvent is valid and matches a specific EventType. Specifically, both methods include repetitive null checks for event and event.type(). This duplication increases maintenance overhead and reduces code clarity.

StreamHelper.java

isToolUseStart

if (event == null || event.type() == null || event.type() != EventType.CONTENT_BLOCK_START) {
    return false;
}

isToolUseFinish

if (event == null || event.type() == null || event.type() != EventType.CONTENT_BLOCK_STOP) {
    return false;
}

Suggest Improvement

public boolean isToolUseStart(StreamEvent event) {
  if (isInvalidEvent(event, EventType.CONTENT_BLOCK_START)) {
      return false;
  }
  ContentBlockStartEvent contentBlockStartEvent = (ContentBlockStartEvent) event;
   return ContentBlock.Type.TOOL_USE.getValue().equals(contentBlockStartEvent.contentBlock().type());   
}

public boolean isToolUseFinish(StreamEvent event) {
   return !isInvalidEvent(event, EventType.CONTENT_BLOCK_STOP);
}

private boolean isInvalidEvent(StreamEvent event, EventType expectedType) {
   return event == null || event.type() == null || event.type() != expectedType;    
}