AgentforceAPI

class AgentforceAPI

Network service layer providing comprehensive API access to Agentforce backend services and conversation management.

Constructor 

1class AgentforceAPI(
2    network: Network,
3    domain: String? = null,
4    sse: AgentforceServerSentEvents,
5    credentialProvider: AgentforceAuthCredentialProvider,
6    instrumentationHandler: AgentforceInstrumentationHandler? = null,
7    configurationLocale: Locale? = null,
8    agentforceLogger: Logger? = null,
9    agentId: String? = null,
10    ioDispatcher: CoroutineDispatcher = Dispatchers.IO
11)

Parameters 

ParameterTypeDescription
networkNetworkNetwork interface for HTTP operations
domainString?Optional Salesforce domain override
sseAgentforceServerSentEventsServer-Sent Events implementation
credentialProviderAgentforceAuthCredentialProviderAuthentication credential management
instrumentationHandlerAgentforceInstrumentationHandler?Analytics and performance monitoring
configurationLocaleLocale?Localization configuration
agentforceLoggerLogger?Logging interface implementation
agentIdString?Default agent identifier
ioDispatcherCoroutineDispatcherCoroutine dispatcher for background operations

Overview 

AgentforceAPI serves as the primary interface for network communication with Agentforce backend services. It handles authentication, request/response processing, real-time event streaming, and error management in a coroutine-friendly architecture.

Core Capabilities 

Essential capabilities of the AgentforceAPI for network communication and conversation management.

Conversation Management 

  • Start and manage agent conversation sessions
  • Send user messages and receive agent responses
  • Handle conversation state transitions
  • Support for conversation persistence and restoration

Real-Time Communication 

  • Server-Sent Events (SSE) for live message streaming
  • Connection management and automatic reconnection
  • Event filtering and processing
  • WebSocket fallback support

Authentication Integration 

  • OAuth 2.0 token management
  • Automatic token refresh
  • Org JWT support for service accounts
  • Secure credential storage and retrieval

Usage Patterns 

Common patterns for initializing and using the AgentforceAPI.

Basic API Setup 

1val networkProvider = MyNetworkImplementation()
2val credentialProvider = MyCredentialProvider()
3val sseService = AgentforceServerSentEvents()
4val logger = MyLoggerImplementation()
5
6val agentforceAPI = AgentforceAPI(
7    network = networkProvider,
8    domain = "https://my-org.salesforce.com",
9    sse = sseService,
10    credentialProvider = credentialProvider,
11    agentforceLogger = logger,
12    agentId = "default-agent-id"
13)

Starting a Conversation 

1class ConversationRepository(private val api: AgentforceAPI) {
2
3    suspend fun startConversation(
4        agentId: String,
5        sessionId: String? = null
6    ): Result<ConversationSession> {
7        return try {
8            val response = api.createConversation(
9                agentId = agentId,
10                sessionId = sessionId
11            )
12            Result.success(response)
13        } catch (e: Exception) {
14            Result.failure(e)
15        }
16    }
17}

Sending Messages 

1suspend fun sendMessage(
2    conversationId: String,
3    message: String,
4    metadata: Map<String, Any> = emptyMap()
5): Result<MessageResponse> {
6    return try {
7        val messageRequest = MessageRequest(
8            text = message,
9            conversationId = conversationId,
10            metadata = metadata
11        )
12
13        val response = api.sendMessage(messageRequest)
14        Result.success(response)
15    } catch (e: Exception) {
16        Result.failure(e)
17    }
18}

Real-Time Event Streaming 

1class ConversationEventHandler(private val api: AgentforceAPI) {
2
3    fun observeConversationEvents(conversationId: String): Flow<ConversationEvent> {
4        return api.subscribeToConversationEvents(conversationId)
5            .catch { exception ->
6                // Handle connection errors
7                handleStreamingError(exception)
8            }
9            .filterIsInstance<ConversationEvent>()
10    }
11
12    private suspend fun handleStreamingError(exception: Throwable) {
13        when (exception) {
14            is NetworkException -> {
15                // Attempt reconnection
16                retryConnection()
17            }
18            is AuthenticationException -> {
19                // Refresh credentials
20                refreshAuthentication()
21            }
22        }
23    }
24}

Error Handling 

Comprehensive error handling patterns for network and API failures.

Network Error Management 

1class ApiErrorHandler {
2
3    suspend fun <T> safeApiCall(
4        apiCall: suspend () -> T
5    ): Result<T> {
6        return try {
7            Result.success(apiCall())
8        } catch (e: HttpException) {
9            when (e.code()) {
10                401 -> Result.failure(AuthenticationException("Token expired"))
11                403 -> Result.failure(AuthorizationException("Insufficient permissions"))
12                429 -> Result.failure(RateLimitException("Too many requests"))
13                else -> Result.failure(NetworkException("API call failed: ${e.message}"))
14            }
15        } catch (e: IOException) {
16            Result.failure(NetworkException("Network connection failed"))
17        }
18    }
19}

Retry Logic 

1class RetryableApiClient(private val api: AgentforceAPI) {
2
3    suspend fun <T> executeWithRetry(
4        maxRetries: Int = 3,
5        backoffMs: Long = 1000,
6        operation: suspend () -> T
7    ): T {
8        repeat(maxRetries) { attempt ->
9            try {
10                return operation()
11            } catch (e: Exception) {
12                if (attempt == maxRetries - 1) throw e
13
14                val delayMs = backoffMs * (2.0.pow(attempt.toDouble())).toLong()
15                delay(delayMs)
16            }
17        }
18        throw IllegalStateException("Retry logic failed")
19    }
20}

Authentication Integration 

Integration patterns for authentication and credential management.

Credential Provider Implementation 

1class MyCredentialProvider : AgentforceAuthCredentialProvider {
2
3    override suspend fun getAuthCredential(): AgentforceAuthCredential {
4        return when (val authType = determineAuthType()) {
5            AuthType.OAUTH -> {
6                AgentforceAuthCredential.OAuth(
7                    authToken = getOAuthToken(),
8                    orgId = getOrgId(),
9                    userId = getUserId()
10                )
11            }
12            AuthType.ORG_JWT -> {
13                AgentforceAuthCredential.OrgJWT(
14                    orgJWT = getOrgJWT()
15                )
16            }
17        }
18    }
19
20    override suspend fun refreshCredential(): AgentforceAuthCredential {
21        // Handle token refresh logic
22        return getAuthCredential()
23    }
24}

Token Management 

1class TokenManager(private val api: AgentforceAPI) {
2
3    private var currentToken: String? = null
4    private var tokenExpiry: Long = 0
5
6    suspend fun getValidToken(): String {
7        if (isTokenExpired()) {
8            refreshToken()
9        }
10        return currentToken ?: throw AuthenticationException("No valid token")
11    }
12
13    private fun isTokenExpired(): Boolean {
14        return System.currentTimeMillis() >= tokenExpiry
15    }
16
17    private suspend fun refreshToken() {
18        val credential = api.credentialProvider.refreshCredential()
19        currentToken = credential.token
20        tokenExpiry = System.currentTimeMillis() + TOKEN_REFRESH_BUFFER
21    }
22}

Server-Sent Events 

Real-time event streaming capabilities for live conversation updates.

Event Stream Management 

1class ConversationEventStream(private val api: AgentforceAPI) {
2
3    fun observeEvents(conversationId: String): Flow<AgentforceEvent> {
4        return api.sse.connect(
5            endpoint = "/conversations/$conversationId/events",
6            headers = mapOf(
7                "Authorization" to "Bearer ${api.getAuthToken()}",
8                "Accept" to "text/event-stream"
9            )
10        ).map { sseEvent ->
11            parseAgentforceEvent(sseEvent)
12        }
13    }
14
15    private fun parseAgentforceEvent(sseEvent: SSEEvent): AgentforceEvent {
16        return when (sseEvent.type) {
17            "message" -> AgentforceMessageEvent.fromJson(sseEvent.data)
18            "typing" -> AgentforceTypingEvent.fromJson(sseEvent.data)
19            "error" -> AgentforceErrorEvent.fromJson(sseEvent.data)
20            else -> AgentforceUnknownEvent(sseEvent.data)
21        }
22    }
23}

Instrumentation and Logging 

Monitoring and logging capabilities for API performance and debugging.

Performance Monitoring 

1class ApiInstrumentation : AgentforceInstrumentationHandler {
2
3    override fun onRequestStarted(request: ApiRequest) {
4        recordEvent("api_request_started") {
5            put("endpoint", request.endpoint)
6            put("method", request.method)
7            put("timestamp", System.currentTimeMillis())
8        }
9    }
10
11    override fun onRequestCompleted(
12        request: ApiRequest,
13        response: ApiResponse,
14        durationMs: Long
15    ) {
16        recordEvent("api_request_completed") {
17            put("endpoint", request.endpoint)
18            put("status_code", response.statusCode)
19            put("duration_ms", durationMs)
20            put("success", response.isSuccessful)
21        }
22    }
23
24    override fun onRequestFailed(request: ApiRequest, error: Throwable) {
25        recordEvent("api_request_failed") {
26            put("endpoint", request.endpoint)
27            put("error_type", error::class.simpleName)
28            put("error_message", error.message)
29        }
30    }
31}

Dependency Integration 

Integration patterns for external dependencies and service providers.

Network Provider Interface 

1interface Network {
2    suspend fun execute(request: NetworkRequest): NetworkResponse
3    suspend fun executeStream(request: StreamRequest): Flow<StreamEvent>
4}
5
6class MyNetworkProvider : Network {
7    private val httpClient = OkHttpClient.Builder()
8        .addInterceptor(AuthenticationInterceptor())
9        .addInterceptor(LoggingInterceptor())
10        .build()
11
12    override suspend fun execute(request: NetworkRequest): NetworkResponse {
13        // Implement HTTP request execution
14        return executeHttpRequest(request)
15    }
16
17    override suspend fun executeStream(request: StreamRequest): Flow<StreamEvent> {
18        // Implement SSE streaming
19        return executeSSERequest(request)
20    }
21}

Configuration Options 

Advanced configuration options for API customization and localization.

For detailed configuration examples including locale and dispatcher configuration, see the Android SDK Developer Guide.

See Also