Add pre/post hooks for structured response generation in create_react_agent

Problem/Use Case

The current create_react_agent function supports pre_model_hook and post_model_hook around the main agent node, but lacks similar hooks around the generate_structured_response node. This limits extensibility when working with structured outputs.

Proposed Solution

Add two new optional parameters to create_react_agent:

  • pre_structured_response_hook: Execute before structured response generation
  • post_structured_response_hook: Execute after structured response generation

Use Cases

Pre-hook examples:

  • Filter/prepare messages before structured output
  • Add context or validation before generation
  • Log or monitor structured response requests

Post-hook examples:

  • Validate generated structured responses
  • Transform or enrich the output
  • Log results or handle errors
  • Apply business rules to responses

Implementation Approach

  • Add hooks as separate workflow nodes (similar to existing pre/post model hooks)
  • Maintain full backward compatibility
  • Support all combinations with existing hooks
  • Works with both tool-calling and non-tool-calling configurations

Example Usage

def prepare_context(state):
  # Pre-process before structured generation
  return {"messages": filtered_messages}

def validate_output(state):
  # Post-process structured response
  response = state["structured_response"]
  # ... validation logic
  return {"structured_response": validated_response}

agent = create_react_agent(
  model="gpt-4",
  tools=[...],
  response_format=MySchema,
  pre_structured_response_hook=prepare_context,
  post_structured_response_hook=validate_output
)

This enhancement would provide consistent hook patterns across the entire react agent workflow.

Current Implementation

I’ve already started working on this and have a working implementation:

Branch: GitHub - rickors560/langgraph at feat/react-agent-pre-post-structured-response-hooks

Key changes:

The implementation maintains full backward compatibility and includes test snapshots for all hook combinations.
This enhancement would provide developers with complete control over the structured response workflow, making LangGraph more flexible for production use cases that require validation, logging, and custom processing.

What do you think about this approach? Would this be valuable for the LangGraph ecosystem?

1 Like

Implementation Progress

I’ve created a draft PR to demonstrate the approach: [DRAFT] feat(prebuilt): add pre/post hooks for structured response in create_react_agent by rickors560 · Pull Request #6258 · langchain-ai/langgraph · GitHub

This shows the complete implementation with tests. Feedback welcome!

1 Like

Closed as team is deprecating create_react_agent in favor of create_agent in langchain !

This functionality is possible via middleware Middleware - Docs by LangChain.