Skip to content

Commit c84cf37

Browse files
KadekMpielas
andauthored
Expose optional Usage field in completions streaming (#374)
Co-authored-by: pielas <[email protected]>
1 parent be5d766 commit c84cf37

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

core/src/main/scala/sttp/openai/requests/completions/chat/ChatChunkRequestResponseData.scala

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package sttp.openai.requests.completions.chat
22

33
import sttp.model.sse.ServerSentEvent
44
import sttp.openai.json.SnakePickle
5+
import sttp.openai.requests.completions.Usage
56

67
object ChatChunkRequestResponseData {
78

@@ -39,7 +40,8 @@ object ChatChunkRequestResponseData {
3940
created: Int,
4041
model: String,
4142
`object`: String,
42-
systemFingerprint: Option[String] = None
43+
systemFingerprint: Option[String] = None,
44+
usage: Option[Usage] = None
4345
)
4446

4547
object ChatChunkResponse {

core/src/test/scala/sttp/openai/requests/completions/chat/ChatChunkDataSpec.scala

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,46 @@ class ChatChunkDataSpec extends AnyFlatSpec with Matchers with EitherValues {
8181
// then
8282
serializedJson shouldBe jsonRequest
8383
}
84+
85+
"Given chat chunk with usage data" should "properly deserialize usage field" in {
86+
import ChatChunkRequestResponseData._
87+
import sttp.openai.requests.completions.Usage
88+
89+
// given
90+
val jsonWithUsage = """{
91+
| "id": "chatcmpl-usage",
92+
| "object": "chat.completion.chunk",
93+
| "created": 1681725687,
94+
| "model": "gpt-4",
95+
| "system_fingerprint": "fp_123",
96+
| "choices": [],
97+
| "usage": {
98+
| "prompt_tokens": 25,
99+
| "completion_tokens": 12,
100+
| "total_tokens": 37
101+
| }
102+
|}""".stripMargin
103+
104+
val expectedResponse = ChatChunkResponse(
105+
id = "chatcmpl-usage",
106+
`object` = "chat.completion.chunk",
107+
created = 1681725687,
108+
model = "gpt-4",
109+
choices = Seq.empty,
110+
systemFingerprint = Some("fp_123"),
111+
usage = Some(
112+
Usage(
113+
promptTokens = 25,
114+
completionTokens = 12,
115+
totalTokens = 37
116+
)
117+
)
118+
)
119+
120+
// when
121+
val givenResponse: Either[Exception, ChatChunkResponse] = JsonUtils.deserializeJsonSnake[ChatChunkResponse].apply(jsonWithUsage)
122+
123+
// then
124+
givenResponse.value shouldBe expectedResponse
125+
}
84126
}

0 commit comments

Comments
 (0)