Quickstart
This page builds the smallest useful flow: configure a model, generate one response, stream one response, and add request options. The same shape is used throughout the SDK.
| You want | Start with |
|---|---|
| One complete answer | generateText |
| UI that updates while text arrives | streamText |
| Typed JSON | generateObject |
| Model-controlled app actions | generateWithTools |
| SwiftUI state without building async plumbing | AIChat or AICompletion |
Create A Model
import SwiftyAI
let model = OpenAICompatibleProvider(
baseURL: "https://api.openai.com/v1",
apiKey: ProcessInfo.processInfo.environment["OPENAI_API_KEY"]!,
model: "gpt-4o-mini"
)Generate Text
Use generateText when your code needs the full answer before it can continue.
let answer = try await generateText(
model: model,
prompt: "What should a Swift developer know before using actors?",
options: GenerationOptions(
system: "Be practical and concise.",
temperature: 0.3,
maxTokens: 300
)
)
print(answer.text)
print(answer.usage?.totalTokens ?? 0)
print(answer.finishReason ?? "unknown")Stream Text
Use streamText when the UI should update as tokens arrive.
var transcript = ""
for try await chunk in streamText(
model: model,
prompt: "Write a short haiku about Swift concurrency."
) {
transcript += chunk.text
print(chunk.text, terminator: "")
}The last chunk may include usage and finish reason if the provider sends that metadata.
Add A Stop Sequence
Options are passed per request. This keeps default model setup separate from request behavior.
let response = try await generateText(
model: model,
prompt: "Return three labels, then write END.",
options: GenerationOptions(
maxTokens: 120,
stopSequences: ["END"],
retryPolicy: RetryPolicy(maxAttempts: 3)
)
)Next Feature
Once the basic call works, move to generate object for typed JSON, tool calling for multi-step work, or SwiftUI hooks for app state.