Commit 9f9e69a
authored
fix: handle Map type in getChatUsage() after deserialization (#1118)
## Summary
`getChatUsage()` returns null when `_chat_usage` metadata is a Map
(after session persistence/reload) instead of a ChatUsage object.
## Why this matters
When messages are persisted via `agent.loadFrom()` and reloaded, JSON
deserialization converts the `_chat_usage` metadata value to a
`Map<String, Object>` instead of a `ChatUsage` instance. The existing
`instanceof ChatUsage` check fails, returning null even though the token
usage data exists in the metadata.
## Changes
`agentscope-core/src/main/java/io/agentscope/core/message/Msg.java`:
- Added Map handling in `getChatUsage()` (line 413): when the metadata
value is a Map, extract `inputTokens`, `outputTokens`, and `time`
fields, build a ChatUsage via the builder, and cache it back in metadata
for subsequent calls
- Added `toInt()` and `toDouble()` helper methods for safe numeric
conversion from deserialized values (handles Integer, Long, Double from
JSON)
## Testing
- When `_chat_usage` is a ChatUsage object: unchanged behavior
- When `_chat_usage` is a Map (post-deserialization): converts to
ChatUsage and returns it
- When `_chat_usage` is null or absent: returns null (unchanged)
- The converted ChatUsage is cached back in metadata so the conversion
only happens once
Fixes #1115
This contribution was developed with AI assistance (Claude Code).
---------
Co-authored-by: Matt Van Horn <[email protected]>1 parent 61369a6 commit 9f9e69a
1 file changed
Lines changed: 30 additions & 1 deletion
Lines changed: 30 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
415 | 415 | | |
416 | 416 | | |
417 | 417 | | |
418 | | - | |
| 418 | + | |
| 419 | + | |
| 420 | + | |
| 421 | + | |
| 422 | + | |
| 423 | + | |
| 424 | + | |
| 425 | + | |
| 426 | + | |
| 427 | + | |
| 428 | + | |
| 429 | + | |
| 430 | + | |
| 431 | + | |
| 432 | + | |
| 433 | + | |
| 434 | + | |
| 435 | + | |
| 436 | + | |
| 437 | + | |
| 438 | + | |
| 439 | + | |
| 440 | + | |
| 441 | + | |
| 442 | + | |
| 443 | + | |
| 444 | + | |
| 445 | + | |
| 446 | + | |
| 447 | + | |
419 | 448 | | |
420 | 449 | | |
421 | 450 | | |
| |||
0 commit comments