SwiftyAISwiftyAI

Search documentation

Find a docs page by title or section

1

SwiftUI Hooks

SwiftyAI includes three observable state helpers for SwiftUI apps:

  • AIChat for multi-turn chat with streaming assistant messages.
  • AICompletion for a single prompt and a single generated output.
  • SwiftyChat for async chat sends managed by your own task.

They are state objects, not UI kits. You still build the view.

HelperState shapeBest for
AIChatmessages, input, isLoading, errorSupport chat, copilots, conversational search, streaming assistants
AICompletioninput / output, isLoading, errorRewrite boxes, title generators, one-shot summaries
SwiftyChatmessages, isStreaming, errorAsync chat flows where the caller awaits send(_:)
Direct model initModel instance passed at constructionPreviews, tests, dependency injection
Model string init"provider/model" plus AI.configureApp-wide provider setup

Chat State

import SwiftUI
import SwiftyAI
 
struct ChatView: View {
    @State private var chat = AIChat(
        model: "openai/gpt-4o-mini",
        systemPrompt: "Be concise.",
        maxMessages: 20
    )
 
    var body: some View {
        VStack {
            List(chat.messages) { message in
                Text(message.content)
            }
 
            HStack {
                TextField("Message", text: $chat.input)
                Button("Send") {
                    chat.send()
                }
                .disabled(chat.isLoading || chat.input.isEmpty)
            }
        }
    }
}

AIChat appends the user message immediately, streams into an assistant message, exposes isLoading, stores error, and supports stop() and reset().

Completion State

struct CompletionView: View {
    @State private var completion = AICompletion(
        model: "openai/gpt-4o-mini",
        options: GenerationOptions(temperature: 0.4)
    )
 
    var body: some View {
        VStack {
            TextEditor(text: $completion.input)
 
            Button("Generate") {
                completion.send()
            }
            .disabled(completion.isLoading)
 
            Text(completion.output)
        }
    }
}

AICompletion also exposes prompt and completion aliases for input and output.

Direct Models

Both helpers also accept direct model instances:

let model = OpenAICompatibleProvider(
    baseURL: "https://api.openai.com/v1",
    apiKey: openAIKey,
    model: "gpt-4o-mini"
)
 
let chat = AIChat(model: model, systemPrompt: "Answer as support.")

Use direct models when previews or tests should not depend on global AI.configure state.

Related docs

Read AIChat, AICompletion, and SwiftyChat for dedicated examples.