Skip to content

Commit 61dd9be

Browse files
committed
Google Gemini - handling a case where Content is empty ({}) with custom Reads and Writes; add test for deserialization of empty content
1 parent 1035371 commit 61dd9be

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

google-gemini-client/src/main/scala/io/cequence/openaiscala/gemini/JsonFormats.scala

+14-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,20 @@ trait JsonFormats {
7979

8080
implicit val partFormat: Format[Part] = Format(partReads, partWrites)
8181

82-
implicit val contentFormat: Format[Content] = Json.format[Content]
82+
implicit val contentWrites: Writes[Content] = (
83+
(__ \ "parts").write[Seq[Part]] and
84+
(__ \ "role").writeNullable[ChatRole]
85+
)(
86+
// somehow unlift(Content.unapply) is not working in Scala3
87+
(x: Content) => (x.parts, x.role)
88+
)
89+
90+
implicit val contentReads: Reads[Content] = (
91+
(__ \ "parts").readWithDefault[Seq[Part]](Nil) and
92+
(__ \ "role").readNullable[ChatRole]
93+
)(Content.apply(_: Seq[Part], _: Option[ChatRole]))
94+
95+
implicit val contentFormat: Format[Content] = Format(contentReads, contentWrites)
8396

8497
// Tools
8598
implicit val toolPrefixFormat: Format[ToolPrefix] = enumFormat(ToolPrefix.values: _*)

google-gemini-client/src/test/scala/io/cequence/openaiscala/gemini/JsonFormatsSpec.scala

+13
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,19 @@ class JsonFormatsSpec extends AnyWordSpecLike with Matchers {
6767
)
6868
}
6969

70+
"deserialize candidate with empty content" in {
71+
testDeserialization[Candidate](
72+
Candidate(
73+
content = Content.apply()
74+
),
75+
"""{
76+
| "content" : {},
77+
| "safetyRatings" : [ ],
78+
| "groundingAttributions" : [ ]
79+
|}""".stripMargin
80+
)
81+
}
82+
7083
"serialize and deserialize top candidate" in {
7184
prettyTestCodec[TopCandidates](
7285
TopCandidates(

0 commit comments

Comments
 (0)