Skip to content
QwryAI
Documentation
Pages

iOS SDK

Streaming

Show your agent's answer as it's written, with async/await and handlers

send streams. It calls your handlers while the answer arrives, runs any client-side actions the agent asks for, and returns the finished answer when it's done. This page covers send, retry and sendNonStreaming, and how to continue or stop an answer.

How streaming works

send(_:conversationId:configure:) is an async throws method on QwryClient. It calls your handlers as the answer arrives, then returns a ChatResponse once the answer is complete.

  • While it runs: your onTextDelta, onToolCall and onToolResult handlers are called.
  • When it succeeds: it returns a ChatResponse.
  • When it fails: it throws a QwryError, or a CancellationError if you cancelled it.

The same call runs your client-side actions. When the agent asks for one, the SDK runs your handler, sends the result back and carries on with the answer. See Client-Side Tools.

send

Swift
@discardableResult
public func send(
    _ text: String,
    conversationId: String? = nil,
    configure: @Sendable (inout SendHandlers) -> Void = { _ in }
) async throws -> ChatResponse

Sends a message, streams the answer, runs any registered tools and returns the finished ChatResponse.

ParameterTypeRequiredDescription
textStringYesThe message to send to your agent.
conversationIdString?NoThe conversation to continue. When nil, the SDK continues currentConversationId, or starts a new conversation if there isn't one.
configure@Sendable (inout SendHandlers) -> VoidNoA closure that sets the handlers you want. Set only the ones you need.
Swift
let response = try await client.send("Where is my order?") { handlers in
    handlers.onTextDelta = { piece in
        print(piece, terminator: "")
    }
    handlers.onToolCall = { call in
        print("Agent is calling: \(call.name)")
    }
    handlers.onToolResult = { result in
        print("Got a result from: \(result.name)")
    }
}

print("\nMessage ID: \(response.message.id)")
print("Finish reason: \(response.finishReason)")

SendHandlers

Swift
public struct SendHandlers: Sendable {
    public var onTextDelta: (@Sendable (String) -> Void)?
    public var onToolCall: (@Sendable (ToolCall) -> Void)?
    public var onToolResult: (@Sendable (ToolResult) -> Void)?
    public init()
}
HandlerWhen it runs
onTextDeltaFor each piece of text as it arrives.
onToolCallWhen the agent calls a tool: one you registered, or one the server runs.
onToolResultWhen a tool finishes, whether your handler ran it or the server did.

Handlers you don't set are ignored. There's no onStart, onFinish or onError; the async throws call covers all three:

Swift
do {
    let response = try await client.send("Hello") { handlers in
        handlers.onTextDelta = { print($0, terminator: "") }
    }
    // Same as onFinish
    show(response)
} catch {
    // Same as onError
    show(error)
}

Showing text as it arrives

Swift
@MainActor
@Observable
final class ChatViewModel {
    var text = ""
    var isSending = false

    private let client: QwryClient

    init(client: QwryClient) { self.client = client }

    func send(_ message: String) async {
        isSending = true
        defer { isSending = false }
        text = ""
        do {
            try await client.send(message) { handlers in
                handlers.onTextDelta = { [weak self] piece in
                    Task { @MainActor in self?.text += piece }
                }
            }
        } catch {
            text = "Something went wrong. Please try again."
        }
    }
}

The client keeps track of the conversation, so each send from this view model continues the same one.

Stopping an answer

Cancelling the Task around send closes the connection. The call then throws CancellationError, never a QwryError.

Swift
var streamTask: Task<Void, Never>?

func start(_ message: String) {
    streamTask = Task {
        do {
            try await client.send(message) { handlers in
                handlers.onTextDelta = { piece in Task { @MainActor in self.append(piece) } }
            }
        } catch is CancellationError {
            // The user stopped it. Keep the text received so far.
        } catch {
            show(error)
        }
    }
}

func stop() {
    streamTask?.cancel()
}

Continuing a conversation

The client remembers the conversation of the last answer in currentConversationId, and send continues it unless you pass another ID:

Swift
// First message: starts a new conversation
let first = try await client.send("My name is Alice.")
print(first.conversationId)

// Continues the same conversation
let second = try await client.send("What is my name?")

To continue a different conversation, pass its ID. To start fresh, clear the current one:

Swift
await client.newConversation()
try await client.send("Fresh start!")

retry

Swift
@discardableResult
public func retry(
    conversationId: String,
    messageId: String,
    configure: @Sendable (inout SendHandlers) -> Void = { _ in }
) async throws -> ChatResponse

Asks the agent to answer again. Streams and runs tools exactly like send.

ParameterTypeRequiredDescription
conversationIdStringYesThe conversation the answer belongs to.
messageIdStringYesThe ID of the agent's message to answer again.
configure@Sendable (inout SendHandlers) -> VoidNoThe same handlers as send.
Swift
let response = try await client.send("Hello")

// Later, from a "Regenerate" button:
let retried = try await client.retry(
    conversationId: response.conversationId,
    messageId: response.message.id
) { handlers in
    handlers.onTextDelta = { print($0, terminator: "") }
}

sendNonStreaming

Swift
@discardableResult
public func sendNonStreaming(
    _ text: String,
    conversationId: String? = nil
) async throws -> ChatResponse

Sends a message and returns the whole answer in one response. There are no handlers, but registered tools still run: the SDK answers each tool call and waits for the rest of the answer before it returns.

ParameterTypeRequiredDescription
textStringYesThe message to send to your agent.
conversationIdString?NoThe conversation to continue. nil continues currentConversationId, or starts a new conversation.
Swift
let response = try await client.sendNonStreaming("Summarize my last order")
print(response.message.text)
print(response.finishReason)  // .stop, .error or .toolCalls
print(response.credits)

Use sendNonStreaming when you don't need to show text as it arrives, such as a background summary.

Which method to use

sendretrysendNonStreaming
Streams textYesYesNo
Runs your toolsYesYesYes
HandlersYesYesNo
Starts a new conversationWhen there's no current oneNeverWhen there's no current one
ReturnsChatResponseChatResponseChatResponse

Explore the documentation