Skip to content

Commit 7d10bcd

Browse files
committed
add unix time + java.time wrappers
1 parent ed1ccd8 commit 7d10bcd

File tree

1 file changed

+40
-9
lines changed

1 file changed

+40
-9
lines changed

src/main/kotlin/com/cjcrafter/openai/chat/ChatResponse.kt

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,26 @@
11
package com.cjcrafter.openai.chat
22

33
import com.google.gson.JsonObject
4+
import java.time.Instant
5+
import java.time.ZoneId
6+
import java.time.ZonedDateTime
7+
import java.util.*
48

59
/**
610
* The [ChatResponse] contains all the data returned by the OpenAI Chat API.
711
* For most use cases, [ChatResponse.get] (passing 0 to the index argument) is
812
* all you need.
913
*
10-
* @property id
11-
* @property object
12-
* @property created
13-
* @property choices
14-
* @property usage
15-
* @constructor Create empty Chat response
14+
* @property id The unique id for your request.
15+
* @property created The Unix timestamp (measured in seconds since 00:00:00 UTC on January 1, 1970) when the API response was created.
16+
* @property choices The list of generated messages.
17+
* @property usage The number of tokens used in this request/response.
18+
* @constructor Create Chat response (for internal usage).
19+
* @see ChatChoice
20+
* @see ChatUsage
1621
*/
17-
class ChatResponse(
22+
data class ChatResponse(
1823
val id: String,
19-
val `object`: String,
2024
val created: Long,
2125
val choices: List<ChatChoice>,
2226
val usage: ChatUsage
@@ -27,12 +31,39 @@ class ChatResponse(
2731
*/
2832
constructor(json: JsonObject) : this(
2933
json["id"].asString,
30-
json["object"].asString,
3134
json["created"].asLong,
3235
json["choices"].asJsonArray.map { ChatChoice(it.asJsonObject) },
3336
ChatUsage(json["usage"].asJsonObject)
3437
)
3538

39+
/**
40+
* Returns the [Instant] time that the OpenAI Chat API sent this response.
41+
* The time is measured as a unix timestamp (measured in seconds since
42+
* 00:00:00 UTC on January 1, 1970).
43+
*
44+
* Note that users expect time to be measured in their timezone, so
45+
* [getZonedTime] is preferred.
46+
*
47+
* @return The instant the api created this response.
48+
* @see getZonedTime
49+
*/
50+
fun getTime(): Instant {
51+
return Instant.ofEpochSecond(created)
52+
}
53+
54+
/**
55+
* Returns the time-zoned instant that the OpenAI Chat API sent this
56+
* response. By default, this method uses the system's timezone.
57+
*
58+
* @param timezone The user's timezone.
59+
* @return The timezone adjusted date time.
60+
* @see TimeZone.getDefault
61+
*/
62+
@JvmOverloads
63+
fun getZonedTime(timezone: ZoneId = TimeZone.getDefault().toZoneId()): ZonedDateTime {
64+
return ZonedDateTime.ofInstant(getTime(), timezone)
65+
}
66+
3667
/**
3768
* Shorthand for accessing the generated messages (shorthand for
3869
* [ChatResponse.choices]).

0 commit comments

Comments
 (0)