Skip to content
Esc
↑↓navigate↵open⌘Jpreview
Start
On this page

Swift SDK

The Swift SDK is the native option in this set: provider-first, async by default, and built for Apple platform apps that want direct control over tools and loop behavior.

Choose a runtime

Use AutohandSDK(configuration:) on macOS when your host needs saved CLI sessions, CLI tool permissions, run budgets, or JSON-RPC notifications. Use the native provider and agent loop on macOS or iOS for in-process execution. See the Swift API reference.

Add the package

// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "MyAgentApp",
    platforms: [.macOS(.v14)],
    dependencies: [
        .package(path: "../AgentSDK")
    ],
    targets: [
        .executableTarget(
            name: "MyAgentApp",
            dependencies: ["AgentSDK"]
        )
    ]
)

Create a first agent

import AgentSDK
import Foundation

let provider = OpenAIProvider(apiKey: "sk-...")
let agent = Agent(
    name: "Reviewer",
    instructions: "Be concise and specific.",
    tools: [.readFile, .bash],
    maxTurns: 10,
    model: ModelID("gpt-4o"),
    provider: provider
)

let output = try await Runner.runSync(
    agent: agent,
    prompt: "Review Sources/App.swift for obvious risks."
)

print(output)

Stream events

Runner.runStream() yields structured events as an async stream.

let stream = Runner.runStream(
    agent: agent,
    prompt: "What files are in the current directory?"
)

for try await event in stream {
    switch event.type {
    case .content:
        if let data = event.data {
            print(data, terminator: "")
        }
    case .toolCall:
        print("\nTool: \(event.tool?.rawValue ?? "unknown")")
    case .done:
        print("\nDone")
    default:
        break
    }
}

Use a permission manager

let hookManager = HookManager()
let permissionManager = PermissionManager(
    hookManager: hookManager,
    mode: .ask
)

Runner.setPermissionManager(permissionManager)

let stream = Runner.runStream(
    agent: agent,
    prompt: "Create a new Swift file and run tests."
)

for try await event in stream {
    if event.type == .content, let data = event.data {
        print(data, terminator: "")
    }
}

Loop strategies

  • .react for the default tool-using loop.
  • .planAndExecute for multi-step task planning.
  • .parallel for independent tasks that can fan out.

Notes

  • With the native runner, pass provider configuration directly in Swift. The macOS CLI client can inherit the provider from the CLI configuration.
  • Built-in tools, hook managers, and permission managers are native Swift types, which makes the SDK a good fit for desktop app integration.

Next steps

Last updated on

Was this helpful?

Send Feedback

Help us improve this documentation page. Your feedback is valuable.

We'll only contact you if we need clarification