1717 */
1818package io .github .malonetalk .agent .tools ;
1919
20- import com .fasterxml .jackson .core . type . TypeReference ;
20+ import com .fasterxml .jackson .annotation . JsonIgnoreProperties ;
2121import com .fasterxml .jackson .databind .ObjectMapper ;
2222import io .agentscope .core .tool .Tool ;
2323import io .agentscope .core .tool .ToolParam ;
2424import java .io .IOException ;
25- import java .io .InputStream ;
25+ import java .net .URI ;
26+ import java .net .http .HttpClient ;
27+ import java .net .http .HttpRequest ;
28+ import java .net .http .HttpResponse ;
29+ import java .nio .charset .StandardCharsets ;
2630import java .time .Clock ;
31+ import java .time .Duration ;
2732import java .time .LocalDate ;
2833import java .time .ZoneId ;
2934import java .time .format .TextStyle ;
30- import java .util . List ;
35+ import java .time . temporal . ChronoUnit ;
3136import java .util .Locale ;
32- import java .util .Map ;
3337import java .util .Optional ;
34- import java .util .concurrent .ConcurrentHashMap ;
3538import org .springframework .beans .factory .annotation .Autowired ;
3639import org .springframework .stereotype .Component ;
3740import org .springframework .util .StringUtils ;
4043public class DateInfoTool implements MarkAgentTool {
4144
4245 private static final String DEFAULT_TIMEZONE = "Asia/Shanghai" ;
43- private static final String PUBLIC_HOLIDAY = "PUBLIC_HOLIDAY" ;
44- private static final String ADJUSTED_WORKDAY = "ADJUSTED_WORKDAY" ;
45- private static final TypeReference <HolidayCalendar > HOLIDAY_CALENDAR_TYPE =
46- new TypeReference <>() {};
46+ private static final String HOLIDAY_API_BASE_URL = "https://timor.tech/api/holiday/info" ;
4747
4848 private final ObjectMapper objectMapper ;
4949 private final Clock clock ;
50- private final Map < Integer , Optional < HolidayCalendar >> calendars = new ConcurrentHashMap <>() ;
50+ private final HttpClient httpClient ;
5151
5252 @ Autowired
5353 public DateInfoTool (ObjectMapper objectMapper ) {
54- this (objectMapper , Clock .systemDefaultZone ());
54+ this (objectMapper , Clock .systemDefaultZone (), HttpClient . newHttpClient () );
5555 }
5656
57- DateInfoTool (ObjectMapper objectMapper , Clock clock ) {
57+ DateInfoTool (ObjectMapper objectMapper , Clock clock , HttpClient httpClient ) {
5858 this .objectMapper = objectMapper ;
5959 this .clock = clock ;
60+ this .httpClient = httpClient ;
6061 }
6162
6263 @ Tool (
6364 name = "get_date_info" ,
6465 description =
6566 """
6667 Get accurate date information, including weekday, weekend, Chinese public \
67- holidays, adjusted workdays, festivals, solar terms and important days. Use \
68- this whenever the user asks about today, a date, weekday, whether a day is a \
69- holiday, or Chinese holiday schedule. For relative dates, convert them using \
70- the system prompt's current date before passing date; omit date for today.\
68+ holidays, holiday schedule adjustments, and optional difference to another \
69+ date. Use this whenever the user asks about today, a date, weekday, whether a \
70+ day is a holiday, Chinese holiday schedule, or date difference. For relative \
71+ dates, convert them using the system prompt's current date before passing \
72+ date; omit date for today. Pass end_date only when a calendar-day difference \
73+ is needed. Date difference counts start date inclusive and end date exclusive.\
7174 """ )
7275 public String getDateInfo (
7376 @ ToolParam (
7477 name = "date" ,
75- description = "Date in yyyy-MM-dd format. Defaults to today." ,
78+ description =
79+ "Date in yyyy-MM-dd format. Defaults to today. Also acts as"
80+ + " start date when end_date is provided." ,
7681 required = false )
7782 String date ,
83+ @ ToolParam (
84+ name = "end_date" ,
85+ description =
86+ "Optional end date in yyyy-MM-dd format for date difference"
87+ + " calculation." ,
88+ required = false )
89+ String endDate ,
7890 @ ToolParam (
7991 name = "timezone" ,
8092 description =
8193 "IANA timezone, e.g. Asia/Shanghai. Defaults to Asia/Shanghai." ,
8294 required = false )
8395 String timezone ) {
8496 try {
85- return objectMapper .writeValueAsString (resolve (date , timezone ));
97+ return objectMapper .writeValueAsString (resolve (date , endDate , timezone ));
8698 } catch (Exception e ) {
8799 return "Error: failed to get date info: " + e .getMessage ();
88100 }
89101 }
90102
91103 DateInfo resolve (String dateText , String timezoneText ) {
104+ return resolve (dateText , null , timezoneText );
105+ }
106+
107+ DateInfo resolve (String dateText , String endDateText , String timezoneText ) {
92108 ZoneId zoneId =
93109 ZoneId .of (StringUtils .hasText (timezoneText ) ? timezoneText : DEFAULT_TIMEZONE );
94110 LocalDate date =
95111 StringUtils .hasText (dateText )
96112 ? LocalDate .parse (dateText )
97113 : LocalDate .now (clock .withZone (zoneId ));
98- Optional <HolidayCalendar > calendar = calendar (date .getYear ());
99- HolidayInfo holidayInfo = calendar .map (c -> c .days ().get (date .toString ())).orElse (null );
100- List <ImportantDay > importantDays =
101- calendar .map (c -> events (c ).getOrDefault (date .toString (), List .of ()))
102- .orElse (List .of ());
103-
104- boolean legalHoliday = holidayInfo != null && PUBLIC_HOLIDAY .equals (holidayInfo .type ());
105- boolean adjustedWorkday =
106- holidayInfo != null && ADJUSTED_WORKDAY .equals (holidayInfo .type ());
114+ Optional <HolidayApiResponse > holidayApiResponse = queryHolidayApi (date );
115+ HolidayDetail holiday = holidayApiResponse .map (HolidayApiResponse ::holiday ).orElse (null );
116+
117+ boolean legalHoliday = holiday != null && Boolean .TRUE .equals (holiday .holiday ());
118+ boolean adjustedWorkday = holiday != null && Boolean .FALSE .equals (holiday .holiday ());
107119 boolean weekend = date .getDayOfWeek ().getValue () >= 6 ;
108- boolean dayOff = legalHoliday || (weekend && !adjustedWorkday );
109120
110121 return new DateInfo (
111122 date .toString (),
112- zoneId .getId (),
113123 date .getDayOfWeek ().getDisplayName (TextStyle .FULL , Locale .CHINA ),
114- date .getDayOfWeek ().getValue (),
115- weekend ,
116- dayOff ,
117- legalHoliday ,
118- adjustedWorkday ,
119- holidayInfo != null ? holidayInfo .name () : null ,
124+ holiday != null ? holiday .name () : null ,
120125 dayType (legalHoliday , adjustedWorkday , weekend ),
121- importantDays ,
122- calendar .isPresent ());
126+ holidayApiResponse .isPresent (),
127+ StringUtils .hasText (endDateText )
128+ ? resolveDateDiff (date , LocalDate .parse (endDateText ))
129+ : null );
123130 }
124131
125- private Optional <HolidayCalendar > calendar (int year ) {
126- return calendars .computeIfAbsent (year , this ::loadCalendar );
132+ DateDiff resolveDateDiff (LocalDate startDate , LocalDate endDate ) {
133+ long calendarDays = ChronoUnit .DAYS .between (startDate , endDate );
134+
135+ return new DateDiff (calendarDays , Math .abs (calendarDays ));
127136 }
128137
129- private Optional <HolidayCalendar > loadCalendar (int year ) {
130- String path = "holidays/cn/" + year + ".json" ;
131- try (InputStream input =
132- Thread .currentThread ().getContextClassLoader ().getResourceAsStream (path )) {
133- if (input == null ) {
138+ private Optional <HolidayApiResponse > queryHolidayApi (LocalDate date ) {
139+ HttpRequest request =
140+ HttpRequest .newBuilder (holidayInfoUri (date ))
141+ .timeout (Duration .ofSeconds (5 ))
142+ .GET ()
143+ .build ();
144+ try {
145+ HttpResponse <String > response =
146+ httpClient .send (
147+ request , HttpResponse .BodyHandlers .ofString (StandardCharsets .UTF_8 ));
148+ if (response .statusCode () != 200 ) {
134149 return Optional .empty ();
135150 }
136- return Optional .of (objectMapper .readValue (input , HOLIDAY_CALENDAR_TYPE ));
151+
152+ HolidayApiResponse body =
153+ objectMapper .readValue (response .body (), HolidayApiResponse .class );
154+ return body .code () == 0 ? Optional .of (body ) : Optional .empty ();
137155 } catch (IOException e ) {
138- throw new IllegalStateException ("failed to load holiday data: " + path , e );
156+ return Optional .empty ();
157+ } catch (InterruptedException e ) {
158+ Thread .currentThread ().interrupt ();
159+ return Optional .empty ();
139160 }
140161 }
141162
163+ private URI holidayInfoUri (LocalDate date ) {
164+ return URI .create (HOLIDAY_API_BASE_URL + "/" + date );
165+ }
166+
142167 private String dayType (boolean legalHoliday , boolean adjustedWorkday , boolean weekend ) {
143168 if (legalHoliday ) {
144169 return "PUBLIC_HOLIDAY" ;
@@ -149,32 +174,22 @@ private String dayType(boolean legalHoliday, boolean adjustedWorkday, boolean we
149174 return weekend ? "WEEKEND" : "WORKDAY" ;
150175 }
151176
152- private Map <String , List <ImportantDay >> events (HolidayCalendar calendar ) {
153- return calendar .events () != null ? calendar .events () : Map .of ();
154- }
155-
156177 record DateInfo (
157178 String date ,
158- String timezone ,
159179 String weekday ,
160- int weekdayIso ,
161- boolean isWeekend ,
162- boolean isDayOff ,
163- boolean isLegalHoliday ,
164- boolean isAdjustedWorkday ,
165180 String holidayName ,
166181 String dayType ,
167- List <ImportantDay > importantDays ,
168- boolean holidayDataAvailable ) {}
182+ boolean holidayDataAvailable ,
183+ DateDiff dateDiff ) {}
184+
185+ record DateDiff (long calendarDays , long absoluteCalendarDays ) {}
169186
170- record HolidayCalendar (
171- int year ,
172- String source ,
173- String sourceUrl ,
174- Map <String , HolidayInfo > days ,
175- Map <String , List <ImportantDay >> events ) {}
187+ @ JsonIgnoreProperties (ignoreUnknown = true )
188+ record HolidayApiResponse (int code , HolidayType type , HolidayDetail holiday ) {}
176189
177- record HolidayInfo (String type , String name ) {}
190+ @ JsonIgnoreProperties (ignoreUnknown = true )
191+ record HolidayType (Integer type , String name , Integer week ) {}
178192
179- record ImportantDay (String type , String name , String time , String note ) {}
193+ @ JsonIgnoreProperties (ignoreUnknown = true )
194+ record HolidayDetail (Boolean holiday , String name , String target , String date ) {}
180195}
0 commit comments