Skip to content

[FEATURE] Flow initialization with Pydantic models having required fields #3629

@visalvo

Description

@visalvo

Feature Area

Core functionality

Bug or Feature?

I don't believe a bug has been filed for this yet, but it could also be considered a bug: it's impossible to have required fields in a Pydantic state model.

Proposed Feature/Bug resolution

TL; DR: Flow initialization fails with Pydantic ValidationError when state model has required fields (maybe more a bug than a feature request). Modify _create_initial_state() to accept and use kwargs when instantiating the state.

Problem
When creating a Flow with a Pydantic BaseModel that has required (non-optional) fields as the state, the initialization fails with a ValidationError. Currently, the only workaround is to make all fields optional (with None defaults), which is not ideal for type safety and data validation.

Current Behavior

from pydantic import BaseModel
from crewai import Flow

class MyState(BaseModel):
    name: str  # Required field
    age: int   # Required field

class MyFlow(Flow[MyState]):
    def __init__(self, **kwargs):
        # implementation

# This fails with ValidationError
flow = MyFlow()  # ❌ ValidationError: Field required for 'name' and 'age'

Expected Behavior
Users should be able to pass initial values as kwargs during Flow instantiation:

# This should work
flow = MyFlow(name="John", age=30)  # ✅ Should initialize state with these values

Root Cause
The _create_initial_state() method is called before any kwargs are processed. When it tries to instantiate a BaseModel with required fields without providing values, Pydantic's validation fails.

The current flow is:

  • __init__() calls _create_initial_state() with no arguments
  • _create_initial_state() tries to instantiate BaseModel: self.initial_state()
  • Pydantic validation fails ❌
  • Only after state creation, _initialize_state(kwargs) is called (which never happens)

Proposed Solution
Modify _create_initial_state() to accept and use kwargs when instantiating the state:

  • Add kwargs parameter to _create_initial_state()
  • Pass kwargs when instantiating BaseModel classes
  • Update __init__() to pass kwargs to _create_initial_state()
  • Keep _initialize_state(inputs) for compatibility with its usage during kickoff

Additional Context
This affects all Flow implementations that want to use strongly-typed state models with required fields, forcing developers to either:

  • Make all fields optional (losing type safety)
  • Use default values for everything (not always appropriate)

Willingness to Contribute

Yes, look at PR #3743

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions