Skip to content

Generate text

Use generateText when you want a complete response before continuing your workflow.

Examples/Sources/GenerateText/main.swift
import SwiftAISDK
@main
struct GenerateTextExample {
static func main() async throws {
let provider = try AIProviders.openAI()
let model = try provider.languageModel("gpt-4.1-mini")
let result = try await model.generateText("Write one sentence about Swift concurrency.")
print(result.text)
}
}

Common options map to provider-agnostic model settings:

  • temperature, topP, topK
  • maxOutputTokens
  • stopSequences
  • seed
  • headers
  • providerOptions
  • extraBody
  • abortSignal
  • retryPolicy, timeoutNanoseconds, and telemetry

Use providerOptions for documented provider-specific behavior. Use extraBody only as a low-level escape hatch when the provider has not yet grown a typed option.

let result = try await model.generateText(
"Be concise.",
options: LanguageGenerationOptions(
providerOptions: [
"openai": [
"parallelToolCalls": false,
"store": false,
],
]
)
)

TextGenerationResult includes the normalized text plus metadata you can use for logging, billing, and debugging:

  • content
  • text
  • reasoning
  • finishReason
  • usage
  • files
  • sources
  • toolCalls
  • toolResults
  • toolApprovalRequests
  • toolApprovalResponses
  • steps
  • responseMessages
  • warnings
  • requestMetadata
  • providerMetadata
  • responseMetadata

content preserves the ordered result parts, including text, reasoning, files, sources, tool calls, tool results, approval requests, approval responses, and custom provider parts. The convenience arrays are derived from the same content when possible.

When you enable tools, steps records each model/tool loop step and responseMessages contains the assistant/tool messages that can be appended to the next request or stored in conversation history.