Skip to content

Commit 9028df4

Browse files
authored
Fix #124 by allowing an empty object for Usage#add method (#125)
1 parent b27bc28 commit 9028df4

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

.changeset/clever-tools-reply.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@openai/agents-core': patch
3+
---
4+
5+
Adjust Usage object to accept empty data

packages/agents-core/src/usage.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,14 @@ export class Usage {
6161
this.inputTokens += newUsage.inputTokens;
6262
this.outputTokens += newUsage.outputTokens;
6363
this.totalTokens += newUsage.totalTokens;
64-
this.inputTokensDetails.push(...newUsage.inputTokensDetails);
65-
this.outputTokensDetails.push(...newUsage.outputTokensDetails);
64+
if (newUsage.inputTokensDetails) {
65+
// The type does not allow undefined, but it could happen runtime
66+
this.inputTokensDetails.push(...newUsage.inputTokensDetails);
67+
}
68+
if (newUsage.outputTokensDetails) {
69+
// The type does not allow undefined, but it could happen runtime
70+
this.outputTokensDetails.push(...newUsage.outputTokensDetails);
71+
}
6672
}
6773
}
6874

packages/agents-core/test/usage.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,11 @@ describe('Usage', () => {
4646
expect(usageA.outputTokens).toBe(5); // 1 + 4
4747
expect(usageA.totalTokens).toBe(9); // 2 + 7
4848
});
49+
50+
it('the add method accepts an empty object', () => {
51+
const usage = new Usage({});
52+
usage.add({} as Usage);
53+
expect(usage.inputTokensDetails).toEqual([]);
54+
expect(usage.outputTokensDetails).toEqual([]);
55+
});
4956
});

0 commit comments

Comments
 (0)