what is the issue with this code and prompt?

from typing import Dict, Any, List, Optional
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, BaseMessage
from langchain.chat_models import init_chat_model
import logging
from pydantic import BaseModel
from langgraph.errors import NodeInterrupt

# Configure logging
logger = logging.getLogger(__name__)

class ReplyNecessityCheckerAgentResponse(BaseModel):
    """Response model for the reply necessity checker."""
    is_necessary: bool
    reason: str = ""  # Optional field to provide reasoning

REPLY_NECESSITY_PROMPT = """
You are a conversation analyst for a trucking logistics company. Your task is to determine if a reply is needed to the latest message in an email thread about a load.

# GUIDELINES

## 1. NO REPLY NEEDED: AUTOMATED & HANDOFF
- Out of office, read receipts, delivery failures.
- Messages indicating someone else will handle the request (e.g., "forwarding to...", "I'll have someone contact you", "let me get a colleague", "escalating to", "passing this to", "handing this over to", "routing this to", "transferring you to").

## 2. NO REPLY NEEDED: SIMPLE ACKNOWLEDGMENTS
- Simple "thank you", "got it", "sounds good".
- A simple confirmation that RESTORES known information without adding new details or questions (e.g., "Confirmed for load #12345").

## 3. REPLY IS REQUIRED: ACTIONABLE MESSAGES
- **Direct questions** about load details, status, or availability.
- **New or updated information** about a load (e.g., "The pickup time has changed to 3 PM").
- **Requests for confirmation or action** (e.g., "Please confirm the rate", "Can you cover this?").
- **Negotiations** about rates or terms.

## 4. WHEN IN DOUBT
If the message is ambiguous or could be interpreted as needing a response, default to is_necessary = True.

# RESPONSE FORMAT
Respond with a JSON object containing:
{
    "is_necessary": boolean,
    "reason": "Brief explanation of your decision"
}

# EXAMPLE RESPONSES
GOOD RESPONSES:
- {"is_necessary": false, "reason": "Simple acknowledgment without requiring response"}
- {"is_necessary": true, "reason": "Message asks a direct question about load details"}
- {"is_necessary": false, "reason": "Automated out of office response"}

BAD EXAMPLES (NEVER DO THIS):
- {"is_necessary": true, "reason": "Thanks for the update!"}  # Should be false for simple thanks
- {"is_necessary": false, "reason": "What's the status?"}  # Should be true for questions
- Using any other format than the specified JSON
- Including placeholders like [example] in responses
- Making assumptions not supported by the message content
"""

def create_reply_necessity_checker_llm(agent_configs: Dict[str, Any]):
    """Create an LLM instance for reply necessity checking with structured output.

    Args:
        agent_configs: Configuration dictionary for the agent

    Returns:
        Configured LLM instance with structured output
    """
    agent_configs = agent_configs if isinstance(agent_configs, dict) else {}
    checker_config = agent_configs.get("reply_necessity_checker", {})

    # Use lower temperature for more deterministic classification
    llm = init_chat_model(
        "azure_openai:gpt-4o",
        temperature=checker_config.get("temperature", 0.0),  # Lower temperature for classification
        model_kwargs={"response_format": {"type": "json_object"}},
    )

    return llm.with_structured_output(ReplyNecessityCheckerAgentResponse)

def format_conversation_history(messages: List[BaseMessage]) -> str:
    """Format conversation history for the prompt.

    Args:
        messages: List of message objects in the conversation

    Returns:
        Formatted string representation of the conversation
    """
    formatted = []
    for msg in messages:
        if isinstance(msg, HumanMessage):
            role = "Broker"
        elif isinstance(msg, AIMessage):
            role = "You"
        else:
            role = "System"
        formatted.append(f"{role}: {msg.content}")
    return "\n\n".join(formatted)



def reply_necessity_checker(state: Dict[str, Any], llm, agent_configs: Dict[str, Any]) -> Dict[str, Any]:
    """
    Determine if a reply is needed to the latest message.

    This node checks if a reply is necessary based on the message content and conversation history.
    It follows LangGraph node conventions by returning only the state updates (empty dict in this case).

    Args:
        state: Current workflow state containing the conversation history
        llm: Initialized language model with structured output
        agent_configs: Configuration for the agent

    Returns:
        Dict[str, Any]: Empty dict as no state updates are needed (following LangGraph pattern)

    Raises:
        NodeInterrupt: If no reply is needed, with reason for skipping
    """
    # Standardize state access - use 'latest_message' and 'messages' as the canonical keys
    latest_message = state.get("latest_message", "")
    messages = state.get("messages", [])
    
    # Format conversation history for the LLM check
    conversation_history = format_conversation_history(messages)
    
    # First, check with LLM if a reply is needed at all
    # This handles handoff/automated messages regardless of missing fields

    try:
        response = llm.invoke([
            SystemMessage(content=agent_configs.get("reply_necessity_checker", {}).get("prompt", REPLY_NECESSITY_PROMPT)),
            HumanMessage(content=f"Conversation history:\n{conversation_history}\n\nLatest received message:\n{latest_message}")
        ])

        if not response.is_necessary:
            raise NodeInterrupt(f"No reply needed - {response.reason}")
            
        # Only after confirming a reply is needed, check if we have missing fields
        if state.get("missing_fields"):
            logger.debug("Reply needed - missing fields require a response")
            return {}

    except Exception as e:
        # Default to replying if there's an error in the LLM call
        # This is a safety measure to avoid missing important communications
        logger.error(
            "Error in reply necessity check. Defaulting to reply.",
            exc_info=True,
            extra={"latest_message": latest_message[:200] if latest_message else ""}
        )
        return {}

    # Return empty dict as per LangGraph node conventions
    # This indicates no state updates are needed, but the graph should continue
    return {}