devstein / langchain

⚡ Building applications with LLMs through composability ⚡
MIT License
1 stars 0 forks source link

TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType' #16

Open devstein opened 1 year ago

devstein commented 1 year ago

System Info

Latest version

Who can help?

me

Information

Related Components

Reproduction

This is a problem with the generative agents.

To reproduce please follow the tutorial outlines here: https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html

When you get to the following line of code you will get an error:

print(tommie.get_summary(force_refresh=True))
File ~/.pyenv/versions/3.9.13/lib/python3.9/site-packages/langchain/retrievers/time_weighted_retriever.py:14, in _get_hours_passed(time, ref_time)
12 def _get_hours_passed(time: datetime.datetime, ref_time: datetime.datetime) -> float:
13 \"\"\"Get the hours passed between two datetime objects.\"\"\"
---> 14 return (time - ref_time).total_seconds() / 3600
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'

Expected behavior

The ref time should be a datetime and tommies summary should be printed.

dosubot[bot] commented 1 year ago

File: langchain/retrievers/time_weighted_retriever.py

To fix the issue, we need to ensure that the last_accessed_at metadata field is always a datetime object. Update the _get_combined_score method to handle the case when the last_accessed_at field is missing or has a None value.

Replace the following lines in the _get_combined_score method:

hours_passed = _get_hours_passed(
    current_time,
    document.metadata["last_accessed_at"],
)

with:

last_accessed_at = document.metadata.get("last_accessed_at")
if last_accessed_at is None:
    last_accessed_at = current_time
    document.metadata["last_accessed_at"] = last_accessed_at

hours_passed = _get_hours_passed(current_time, last_accessed_at)

This change ensures that if the last_accessed_at field is missing or has a None value, it will be set to the current time before calculating the hours passed.