Skip to content

Commit

Permalink
@W-16589742: [iOS] REST wrappers for select SFAP APIs (Team-Review Up…
Browse files Browse the repository at this point in the history
…dates)
  • Loading branch information
JohnsonEricAtSalesforce committed Jan 14, 2025
1 parent a401e1a commit 70101dc
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@ import Foundation
@objc(SFApApiClient)
public class SfapApiClient : NSObject {

/// The error domain
static let errorDomain = "com.salesforce.sfap_api.client"

/// The sfap_api hostname
private let apiHostName: String

Expand Down Expand Up @@ -64,13 +61,8 @@ public class SfapApiClient : NSObject {
) async throws -> SfapApiGenerationsResponseBody {

// Guards.
guard
let userAccountCurrent = UserAccountManager.shared.currentUserAccount,
let restClient = RestClient.restClient(for: userAccountCurrent) else {
throw sfapApiErrorWithMessage("Cannot invoke sfap_api client without a current user account.")}

guard let modelNameUnwrapped = modelName else {
throw sfapApiErrorWithMessage("Cannot fetch generated embeddings without specifying a model name.")
guard let modelName = modelName else {
throw sfapApiError(message: "Cannot fetch generated embeddings without specifying a model name.")
}

// Generate the sfap_api generations request body.
Expand All @@ -81,16 +73,16 @@ public class SfapApiClient : NSObject {
),
encoding: .utf8)
} catch let error {
throw sfapApiErrorWithMessage("Cannot JSON encode sfap_api generations request body due to an encoding error with description '\(error.localizedDescription)'.")
throw sfapApiError(message: "Cannot JSON encode sfap_api generations request body due to an encoding error with description '\(error.localizedDescription)'.")
}}() else {
throw sfapApiErrorWithMessage("Cannot JSON encode sfap_api generations request body.")
throw sfapApiError(message: "Cannot JSON encode sfap_api generations request body.")
}

// Create the sfap_api generations request.
let sfapApiGenerationsRequest = RestRequest(
method: .POST,
baseURL: "https://\(apiHostName)/",
path: "einstein/platform/v1/models/\(modelNameUnwrapped)/generations",
path: "einstein/platform/v1/models/\(modelName)/generations",
queryParams: nil)
sfapApiGenerationsRequest.customHeaders = [
"x-sfdc-app-context" : "EinsteinGPT",
Expand All @@ -117,33 +109,44 @@ public class SfapApiClient : NSObject {

case .success(let sfapApiGenerationsResponse):
// Decode the sfap_api generations response.
guard let sfapApiGenerationsResponseBody = try {
do {
return try sfapApiGenerationsResponse.asDecodable(type: SfapApiGenerationsResponseBody.self)
} catch let error {
throw sfapApiErrorWithMessage("Cannot JSON decode sfap_api generations response body due to a decoding error with description '\(error.localizedDescription)'.")
}}() else {
throw sfapApiErrorWithMessage("Cannot JSON decode sfap_api generations response body.")
}
let sfapApiGenerationsResponseBody = try sfapApiGenerationsResponse.asDecodable(
type: SfapApiGenerationsResponseBody.self
)
return sfapApiGenerationsResponseBody

case .failure(let error):
throw sfapApiErrorWithMessage("sfap_api generations request failure with description '\(error.localizedDescription)'.")
switch error {

case .apiFailed(
response: let response,
underlyingError: _,
urlResponse: _
): if let errorResponseData = response as? Data {
let sfapApiErrorResponseBody = try JSONDecoder().decode(SfapApiErrorResponseBody.self, from: errorResponseData)
throw sfapApiError(
errorCode: sfapApiErrorResponseBody.errorCode,
message: "sfap_api generations request failure with description: '\(error.localizedDescription)', message: '\(String(describing: sfapApiErrorResponseBody.message))'.",
messageCode: sfapApiErrorResponseBody.messageCode,
source: String(data: errorResponseData, encoding: .utf8))
} else { throw error }

default: throw error
}
}
}

private func sfapApiErrorWithMessage(_ message: String) -> SfapApiError {

SFSDKCoreLogger().e(
classForCoder,
message: message)
private func sfapApiError(
errorCode: String? = nil,
message: String,
messageCode: String? = nil,
source: String? = nil) -> SfapApiError
{
SFSDKCoreLogger().e(classForCoder, message: message)

return SfapApiError(
domain: SfapApiClient.errorDomain,
code: -1,
userInfo: [NSLocalizedDescriptionKey : message],
errorCode: errorCode,
message: message,
messageCode: nil,
source: nil)
messageCode: messageCode,
source: source)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,37 +29,15 @@

import Foundation

/// An exception derived from an `sfap_api` endpoint failure response.
/// An error derived from an `sfap_api` endpoint failure response.
/// See https://developer.salesforce.com/docs/einstein/genai/guide/access-models-api-with-rest.html#step-3-use-models-rest-api
/// @param errorCode The `sfap_api` error code
/// @param message The `sfap_api` error message
/// @param messageCode The `sfap_api` error code
/// @param source The original `sfap_api` error response body
@objc
public class SfapApiError : NSError, @unchecked Sendable {
public struct SfapApiError: Error {

var errorCode: String? = nil
var message: String? = nil
var messageCode: String? = nil
var source: String? = nil

public required init?(
coder: NSCoder
) {
super.init(coder: coder)
}

public init(
domain: String,
code: Int,
userInfo: [String : Any]? = nil,
message: String?,
messageCode: String?,
source: String?
) {
super.init(domain: domain, code: code, userInfo: userInfo)
self.message = message
self.messageCode = messageCode
self.source = source
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
SfapApiErrorResponseBody.swift
SalesforceSDKCore

Created by Eric C. Johnson ([email protected]) on 20250114.

Copyright (c) 2025-present, salesforce.com, inc. All rights reserved.

Redistribution and use of this software in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written
permission of salesforce.com, inc.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import Foundation

/**
Models error responses from the `sfap_api` endpoints.
See https://developer.salesforce.com/docs/einstein/genai/references/models-api?meta=Summary
*/
struct SfapApiErrorResponseBody: Codable {

/// The response error code
public let errorCode: String?

/// The response message
public let message: String?

/// The response message code
public let messageCode: String?

enum CodingKeys: String, CodingKey {
case errorCode = "errorCode"
case message = "message"
case messageCode = "messageCode"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,4 @@ struct SfapApiGenerationsRequestBody: Codable {
enum CodingKeys: String, CodingKey {
case prompt = "prompt"
}

/// Returns a JSON representation of this sfap_api generations request body.
/// - Returns: A JSON representation of this sfap_api generations request body or nil if a value
/// cannot be returned for any reason. A log entry will be output when nil is returned do to an error
///
func toJson() -> String? {
// Generate the start registration request body.
guard let startRegistrationRequestBodyString = {
do { return String(
data: try JSONEncoder().encode(self),
encoding: .utf8)
} catch let error {
SFSDKCoreLogger().e(
SfapApiClient.classForCoder(),
message: "Cannot JSON encode sfap_api generations request body due to an encoding error with description '\(error.localizedDescription)'.")
return nil
}}() else { return nil }
return startRegistrationRequestBodyString
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -161,25 +161,4 @@ public class SfapApiGenerationsResponseBody: NSObject, Codable {
}
}
}

/// Returns an `sfap_api` "generations" endpoint response from the JSON text.
/// - Parameters:
/// - json The JSON text
/// - Return: The `sfap_api` "generations" endpoint response body or nil if a value cannot be
/// returned for any reason. A log entry will be output when nil is returned do to an error
static func fromJson(json: String) -> SfapApiGenerationsResponseBody? {
guard let result: SfapApiGenerationsResponseBody? = {
do {
if let data = json.data(using: .utf8) {
return try JSONDecoder.init().decode(SfapApiGenerationsResponseBody.self, from: data)
} else { return nil }
} catch let error {
SFSDKCoreLogger().e(
SfapApiClient.classForCoder(),
message: "Cannot JSON decode sfap_api generations request body due to a decoding error with description '\(error.localizedDescription)'.")
return nil
}}() else { return nil }
result?.sourceJson = json
return result
}
}

0 comments on commit 70101dc

Please sign in to comment.