mirror of
https://github.com/langgenius/dify.git
synced 2026-09-09 05:41:00 +08:00
fix(api): handle string and missing params in weekday time tool (#41952)
This commit is contained in:
parent
f3154e347e
commit
80428a693a
@ -35,20 +35,23 @@ class WeekdayTool(BuiltinTool):
|
||||
return
|
||||
|
||||
weekday_name = calendar.day_name[date_obj.weekday()]
|
||||
month_name = calendar.month_name[month]
|
||||
month_name = calendar.month_name[date_obj.month]
|
||||
readable_date = f"{month_name} {date_obj.day}, {date_obj.year}"
|
||||
yield self.create_text_message(f"{readable_date} is {weekday_name}.")
|
||||
|
||||
@staticmethod
|
||||
def convert_datetime(year, month, day) -> datetime | None:
|
||||
try:
|
||||
# allowed range in datetime module
|
||||
if not (year >= 1 and 1 <= month <= 12 and 1 <= day <= 31):
|
||||
if year is None or month is None or day is None:
|
||||
return None
|
||||
|
||||
year = int(year)
|
||||
month = int(month)
|
||||
day = int(day)
|
||||
# allowed range in datetime module
|
||||
if not (year >= 1 and 1 <= month <= 12 and 1 <= day <= 31):
|
||||
return None
|
||||
|
||||
return datetime(year, month, day)
|
||||
except ValueError:
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
@ -143,6 +143,23 @@ def test_weekday_tool(sqlite_session: Session):
|
||||
with pytest.raises(ValueError, match="Month is required"):
|
||||
list(weekday_tool.invoke(session=sqlite_session, user_id="u", tool_parameters={"year": 2024, "day": 1}))
|
||||
|
||||
# LLMs often send numeric parameters as strings; these must be accepted.
|
||||
string_params = list(
|
||||
weekday_tool.invoke(
|
||||
session=sqlite_session, user_id="u", tool_parameters={"year": "2024", "month": "3", "day": "5"}
|
||||
)
|
||||
)[0].message.text
|
||||
expected_date = date(2024, 3, 5)
|
||||
assert string_params == (
|
||||
f"{calendar.month_name[expected_date.month]} "
|
||||
f"{expected_date.day}, {expected_date.year} "
|
||||
f"is {calendar.day_name[expected_date.weekday()]}."
|
||||
)
|
||||
# Missing or non-numeric values must yield an "Invalid date" message, not crash.
|
||||
for params in ({"year": 2024, "month": 3}, {"year": "abc", "month": 3, "day": 5}):
|
||||
result = list(weekday_tool.invoke(session=sqlite_session, user_id="u", tool_parameters=params))[0].message.text
|
||||
assert "Invalid date" in result
|
||||
|
||||
|
||||
def test_simple_code_valid_execution(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session):
|
||||
simple_code = _build_builtin_tool(SimpleCode)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user