SwiftUI Hooks
SwiftyAI includes three observable state helpers for SwiftUI apps:
AIChatfor multi-turn chat with streaming assistant messages.AICompletionfor a single prompt and a single generated output.SwiftyChatfor async chat sends managed by your own task.
They are state objects, not UI kits. You still build the view.
| Helper | State shape | Best for |
|---|---|---|
AIChat | messages, input, isLoading, error | Support chat, copilots, conversational search, streaming assistants |
AICompletion | input / output, isLoading, error | Rewrite boxes, title generators, one-shot summaries |
SwiftyChat | messages, isStreaming, error | Async chat flows where the caller awaits send(_:) |
| Direct model init | Model instance passed at construction | Previews, tests, dependency injection |
| Model string init | "provider/model" plus AI.configure | App-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.