AIConversationTransport

How an AIConversationState reaches the agent and learns what it holds: it sends what the person asks, stops the agent, and tells the state its messages as they change.

With Stream Chat, the conversation is a channel: the transport follows its messages and AI indicator events, and sends each request through the channel or your agent's own API.

class AgentTransport(
private val channel: ChannelState,
private val agent: AgentApi,
private val scope: CoroutineScope,
) : AIConversationTransport<AgentMessage> {

override fun connect(feed: AIConversationFeed<AgentMessage>) {
scope.launch {
channel.messages.collect { messages -> feed.update(messages = messages.map(::AgentMessage)) }
}
}

override suspend fun send(request: AIConversationRequest<AgentMessage>) {
agent.respond(request.text, files = request.attachments)
}

override suspend fun stop() {
agent.interrupt()
}
}

The state calls it on the thread of its scope, the main thread for a viewModelScope.

Functions

Link copied to clipboard
abstract fun connect(feed: AIConversationFeed<M>)

Starts telling feed what the conversation holds: its messages each time they change, whether there are older ones to load, and what the agent says it is doing. The state calls it once, as it is made. Call the feed on the state's thread.

Link copied to clipboard
open suspend fun loadOlderMessages()

Loads the messages before the first one, which arrive through the feed. Does nothing by default.

Link copied to clipboard
open suspend fun rate(reply: M, rating: AIMessageRating?)

Tells your backend how the person rated a reply, or that they took their rating back with null. Does nothing by default: the state keeps the ratings on this device either way.

Link copied to clipboard
abstract suspend fun send(request: AIConversationRequest<M>)

Sends what the person asks. Return once the agent has the request: its reply arrives through the feed. A thrown exception shows as the state's error, and the person can retry, which sends the same request again with the same AIConversationRequest.messageId: if the first attempt reached your backend, or you keep a copy of the failed message, use the id so the message isn't added twice.

Link copied to clipboard
abstract suspend fun stop()

Stops the reply the agent is writing. What it wrote so far stays.