TypeError
builtins.TypeError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
result = instructor_model.process_response(response)
File "/usr/local/lib/python3.10/site-packages/instructor/model.py", line 88, in process_response
length = len(response.optional_field) # This line causes TypeError
TypeError: object of type 'NoneType' has no len() Why it happens
Instructor models define some fields as optional, which can be None if the LLM does not provide a value. When downstream code tries to use these fields without checking for None, it causes TypeError exceptions. This happens because optional fields are not guaranteed to be present in the response.
Detection
Add validation or assertions after receiving the response to check if optional fields are None before accessing or calling methods on them.
Causes & fixes
Optional field in the Instructor response is None but code assumes it is a string or list.
Add explicit None checks before accessing or calling methods on optional fields returned by the Instructor model.
Prompt or model configuration does not guarantee the optional field is always returned.
Adjust the prompt or model parameters to ensure the optional field is always included or provide a default fallback value in code.
Incorrect type hinting or missing Optional in type annotations leading to unsafe assumptions.
Use Optional[...] type hints in your data models and handle None cases explicitly in your code.
Code: broken vs fixed
from instructor import Instructor
instructor_model = Instructor()
response = instructor_model.get_response(input_text)
# This line causes TypeError if optional_field is None
length = len(response.optional_field) # broken code import os
from instructor import Instructor
os.environ['INSTRUCTOR_API_KEY'] = os.environ.get('INSTRUCTOR_API_KEY', '') # Use env var for API key
instructor_model = Instructor()
response = instructor_model.get_response(input_text)
# Fixed: Check for None before using optional_field
if response.optional_field is not None:
length = len(response.optional_field)
else:
length = 0 # or some default
print(f'Optional field length: {length}') Workaround
Wrap access to optional fields in try/except TypeError blocks and provide fallback values if None is encountered.
Prevention
Design your data models with Optional types and always validate or sanitize LLM responses before usage to handle missing optional fields gracefully.