Swift Examples - Brave Search

Service setup

Create a Brave Search service in the AIProxy dashboard

Follow the integration guide, selecting the Brave Search icon on the 'Create a New Service' form.

import AIProxy

/* Uncomment for BYOK use cases */
// let braveService = AIProxy.braveDirectService(
//     unprotectedAPIKey: "your-brave-key"
// )

/* Uncomment for all other production use cases */
// let braveService = AIProxy.braveService(
//     partialKey: "partial-key-from-your-developer-dashboard",
//     serviceURL: "service-url-from-your-developer-dashboard"
// )

do {
    let searchResult = try await braveService.webSearchRequest(query: "How does concurrency work in Swift 6")
    let resultCount = searchResult.web?.results?.count ?? 0
    let urls = searchResult.web?.results?.compactMap { $0.url }
    print(
        """
        Brave responded with \(resultCount) search results.
        The search returned these urls: \(urls ?? [])
        """
    )
} catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) {
    print("Receivedt non-200 status code: \(statusCode) with response body: \(responseBody)")
} catch {
    // You may want to catch additional Foundation errors and pop the appropriate UI
    // to the user. See "How to catch Foundation errors for specific conditions" here:
    // https://www.aiproxy.com/docs/integration-options.html
    print("Could not make brave search: \(error.localizedDescription)")
}