Skip to content

Commit e6442b4

Browse files
Implement custom encoding and decoding for FunctionCallDetails to handle JSON string for arguments
1 parent 15a5455 commit e6442b4

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

Sources/Grok-API-SDK/Models/FunctionCall.swift

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,33 @@ public struct ToolCall: Codable, Sendable {
8080

8181
public struct FunctionCallDetails: Codable, Sendable {
8282
public let name: String
83-
public let arguments: [String: String] // Change to dictionary to match JSON response
83+
public let arguments: [String: String]
84+
85+
// Custom decoding to handle JSON string for arguments
86+
public init(from decoder: Decoder) throws {
87+
let container = try decoder.container(keyedBy: CodingKeys.self)
88+
name = try container.decode(String.self, forKey: .name)
89+
let argumentsString = try container.decode(String.self, forKey: .arguments)
90+
if let data = argumentsString.data(using: .utf8),
91+
let argumentsDict = try? JSONDecoder().decode([String: String].self, from: data) {
92+
arguments = argumentsDict
93+
} else {
94+
arguments = [:]
95+
}
96+
}
8497

85-
// Explicit public initializer
86-
public init(name: String, arguments: [String: String]) {
87-
self.name = name
88-
self.arguments = arguments
98+
// Custom encoding to handle JSON string for arguments
99+
public func encode(to encoder: Encoder) throws {
100+
var container = encoder.container(keyedBy: CodingKeys.self)
101+
try container.encode(name, forKey: .name)
102+
let argumentsData = try JSONEncoder().encode(arguments)
103+
let argumentsString = String(data: argumentsData, encoding: .utf8) ?? "{}"
104+
try container.encode(argumentsString, forKey: .arguments)
105+
}
106+
107+
enum CodingKeys: String, CodingKey {
108+
case name
109+
case arguments
89110
}
90111
}
91112

0 commit comments

Comments
 (0)