Changelog
What shipped in each release of swift-ai-sdk.
0.3.0
The long-run release.
Agents break deep into a run, not on the first call. This release is about what happens at step fifty: staying inside the context window without forgetting what you learned, stopping when you say so, asking before acting, and signing in to hosted MCP servers. Plus a terminal you can watch it all happen in, Meta's Muse Spark as a new provider, and a large expansion of the Anthropic, OpenAI, Google, xAI, and Bedrock platform surfaces.
Compaction
Keep a long run inside the window without losing the goal, the decisions, or the dead ends.
Timeouts and approvals
Bound a run at every scope. Signed approvals that fail closed.
Terminal UI
Run any Agent as an interactive terminal chat in one call.
MCP OAuth
Sign in to hosted MCP servers. A 401 refreshes and retries.
Runtime context
Server state through a run, never in the prompt.
Providers
OpenAI multi-agent, Google's Interactions API, Meta and Bedrock mantle.
Terminal UI
- New
AITUIlibrary product, the@ai-sdk/tuianalog, on macOS and Linux.runAgentTUI(title:agent:)(ortransport:) runs an interactive terminal chat over anyAgentorChatTransport. - What you get in it: streamed markdown, tool cards, reasoning sections,
scrollback, tokens/sec and context readouts, and
y/ntool approvals. TerminalPartDisplayMode(.full/.collapsed/.autoCollapsed/.hidden) for tools and reasoning, andResponseStatisticsModefor the statistics readout.- The renderers are public and pure:
MarkdownTerminalRenderer,TranscriptRenderer,AgentTUIModel, andAgentTUIRendererwork without a terminal, so transcripts can be rendered anywhere. swift run tui-demois a runnable demo backed by real models only:--ollama(local, no API key),--openai,--anthropic,--on-device, or--pcc. With no flag it picks the first usable backend and otherwise prints how to get one.- The demo verifies an Ollama server is reachable and the model is actually
pulled before starting (
--listshows what is), and its weather tool calls a live API, so tool cards show real data.
Context management
compaction:ongenerateText/streamText/Agentkeeps a long run inside the window without discarding what it learned.- It compresses in proportion to how cheaply information can be recovered. Bulk tool output is re-fetchable, so it compresses hard. A decision's rationale exists only in the transcript, so it is kept.
- Three layers, the first two free: structural pinning (system messages, the
goal, failed tool results, the last N steps), a live-reference scan that pins
older messages still mentioned by the working set, then one
generateObjectcall over the remainder using the run's own model. CompactedContextis a required-field schema rather than a prose summary, sogoal,decisions, anddeadEndscannot be silently dropped.- Dead ends are the entry most summarizers lose and the costliest, since an agent that forgets a failed approach retries it. Compaction is re-entrant, so a long run converges instead of growing.
Tool.idempotent()marks a tool whose result may be replaced by a pointer ([omitted: … re-run the tool to retrieve it]). The tool call is always kept, since it records what was tried. Off by default, so tools with side effects keep their output in full.CompactionBudgetallocates fractions of the context window instead of a single threshold, so one config behaves correctly across model tiers.LanguageModelgainedcontextWindow, with a default implementation that resolves from the model id, so every provider pack reports a window with no per-provider wiring and a budget left unset sizes itself to the model.ModelContextWindows.register(_:for:)covers local, fine-tuned, and newly released ids.- Unknown ids fall back to 128K, deliberately below the common 200K: under-estimating compacts early, while over-estimating overflows the window and fails the request.
pruneMessagesis the lossy counterpart: it drops old tool traffic (and, forUIMessagehistories, reasoning) outright, with no model call.
Timeouts and approvals
timeout:ongenerateText/streamText/Agent:GenerationTimeout(total:step:firstChunk:chunk:tool:tools:). The stall timers count only content-bearing output, so keep-alive metadata cannot hold a dead stream open. Tool timeouts return a tool error the model can react to; the others throwAIError.timedOut.toolApproval:moves approval policy onto the call: a dictionary literal,ToolApprovalPolicy.perTool, or a closure over the whole tool call with the message history.- Decisions are
.notApplicable/.approved/.denied/.userApproval, each with an optional reason, and land onstep.approvalDecisions.prepareCallcan return one, and per-toolneedsApprovalstill works as the fallback. toolApprovalSecret:HMAC-signs approval requests and verifies them fail-closed on replay, so a client cannot forge an approval for a tool it was never offered. Signatures ride the UI-message wire, andChatSessionand the terminal UI carry them back automatically.
MCP: OAuth for hosted servers
MCPOAuthSessionties anMCPOAuthClientProviderto one server and is passed to a transport asauth:. BothMCPHTTPTransportandMCPSSETransportaccept it.- It attaches the access token, refreshes on a
401, and retries once. Otherwise it throwsAIError.authorizationRequired(url:)with the URL to open; hand the browser's redirect back tocomplete(callbackURL:)to finish. - Full MCP discovery: the
401'sWWW-Authenticatenames the protected-resource metadata document (RFC 9728), which names the authorization server — commonly a different host than the MCP server, so the single-host shortcut most clients take does not work. - Well-known URLs follow RFC 8414, keeping the issuer path (
/tenant/acme→/.well-known/oauth-authorization-server/tenant/acme) with the origin-only form as fallback. - PKCE
S256(and a clear error rather than a silent downgrade toplainwhere CryptoKit is unavailable), the RFC 8707resourceindicator on the authorization, token, and refresh requests,stateverification on the callback, and dynamic client registration when the server advertises aregistration_endpoint. MCPOAuthFlowexposes each step (discover,registerClientIfNeeded,startAuthorization,handleCallback,refresh) for apps that drive the flow themselves.
Runtime context and tools
runtimeContext:carries server-side state through a run without touching the prompt: readable inprepareStep, replaceable from there, and recorded on everyStepResult.- Tools can validate their
toolsContextentry with.withContextSchema(_:)and compute their description from it with.describing { context in ... }. Tool.dynamic(...)marks runtime-schema tools, carried asdynamicon the tool chunks so a UI can tell them from compiled-in tools. MCP tools are dynamic automatically.TelemetrySettingsadds a per-call function id, metadata, an off switch, and allow-lists (includeRuntimeContext/includeToolsContext) for which context keys reach spans. Nothing from either context is recorded unless you name it.filterActiveTools,generateId/createIdGenerator, andGeneratedFileaccessors (base64,bytes) on image results.- New provider-defined tools: OpenAI
imageGeneration,shell,localShell,applyPatch,customTool,toolSearch,programmaticToolCalling, and hostedmcpServer; Anthropicadvisor,toolSearchBm25,toolSearchRegex; GooglevertexRagStore.
Files and remote content
uploadFile(api:data:filename:)works with anyFileUploadAPIand returns anUploadedFileyou can turn into a message part.providerReferenceonFileContent/ImageContentreaches OpenAI asfile_idand Anthropic as afilesource, and is ignored by providers it was not minted for.- Models declare URL support with
supportsRemoteURL(_:mediaType:), and the loop downloads and inlines what a model cannot fetch.
Middleware
wrapEmbeddingModel,wrapImageModel, andwrapProviderextend middleware beyond language models..extractJson()strips markdown code fences;.addToolInputExamples()folds a tool's newinputExamplesinto its description.
Transcription
streamTranscribetranscribes live audio throughStreamingTranscriptionModel, implemented for Deepgram's live WebSocket API. Interim text arrives as.partialTranscriptand finalized text as.transcriptDelta, so revisions never double-count.transcribesniffs MP4/M4A, WAV, Ogg, FLAC, and MP3 from the audio bytes when the declared media type is generic.resampleAudio,encodePCM16, anddecodePCM16for feeding realtime and streaming audio paths.
Chat UI and transports
TextStreamChatTransport,consumeStream,validateUIMessages/safeValidateUIMessages, andlastAssistantMessageIsCompleteWithToolCalls/lastAssistantMessageIsCompleteWithApprovalResponses.HTTPChatTransportgainedprepareSendMessagesRequestandprepareReconnectToStreamRequestfor per-request headers, body, and URL.
Anthropic
- Every tool now carries Anthropic's optional definition properties through
Tool.loading(_:):strict(schema-validated tool names and inputs),defer_loading(keep a tool out of the cached system prompt until tool search surfaces it),allowed_callers(restrict a tool to the code execution sandbox),cache_controlbreakpoints, andeager_input_streaming..ephemeralCache()and.codeExecutionOnly()are shorthands. inputExamplesnow ship natively asinput_exampleson Anthropic instead of being folded into the description.AnthropicModel.Tools.mcpToolset(...)wires the MCP connector, with themcp-client-2025-11-20beta header applied automatically. Beta headers also cover the newest tool versions (web_search_20260318,web_fetch_20260318/20260309,code_execution_20260521).AnthropicBatchClient(Message Batches: create, list, retrieve, streamed JSONLresults, cancel, delete),AnthropicModelsClient, andAnthropicModel.countTokens(_:tools:system:).
OpenAI
- Multi-agent on the Responses API: pass
multiAgent: OpenAIModel.MultiAgent(maxConcurrentSubagents: 3)and the model spawns and coordinates a subagent tree itself. Theresponses_multi_agent=v1beta header is added for you. - Hosted
multi_agent_callitems (spawn, message, follow-up, wait, interrupt, list) surface as provider metadata rather than tool calls, so your app must not execute them. Ordinary function calls from any agent in the tree still run through the normal tool loop. OpenAIConversationsClientfor the Conversations API: create (from messages or raw items), fetch, update metadata, list/add/delete items.OpenAIVectorStoresClientincludingsearch, file attach/detach, and expiry windows, the store side offile_search.OpenAIBatchClient,OpenAIContainersClient, andOpenAIModerationsClient(which returns the flagged categories, sorted).OpenAIVideoModelfor Sora: create, poll to completion, download content, plusremix,list, anddelete.
GoogleInteractionsModelspeaks Google's newerPOST /v1beta/interactionssurface, the one they say all new models, tools, and agentic features now launch on, whilegenerateContent(stillGoogleModel) is labelled legacy.- Messages map to
inputsteps, thought steps arrive as.reasoningDelta, and the SSEstep.start/step.delta/step.stopprotocol decodes into ordinary stream parts. - Server-side state via
previousInteractionID,background: truefor long runs, andcreate/retrieve/cancel/delete.storedefaults tofalseeven though Google's API defaults it totrue, so nothing is retained unless you opt in. - Agents share the endpoint:
GoogleInteractionsModel.agent(…)reaches Deep Research and Antigravity, withagentConfigreplacinggeneration_config. GoogleEmbeddingModel(embedContent/batchEmbedContents, task types, output dimensionality). Gemini embeddings were previously unsupported.- Media:
GoogleImageModel(Imagen),GoogleVideoModel(Veo, with operation polling and URI download),GoogleSpeechModel(Gemini TTS), andGoogleMusicModel(Lyria). - Platform:
GoogleFilesClient(resumable upload pluswaitUntilActive),GoogleCachedContentClient(explicit context caching),GoogleBatchClient(batchGenerateContentandasyncBatchEmbedContent), andGoogleModel.countTokens.
xAI
- Fixed:
XaiCollectionsClientsent collection management toapi.x.ai, but xAI serves it fromhttps://management-api.x.ai/v1behind a separate Management API key. The client now holds both endpoints and routes each call, andaddDocumentputs the file id in the path (POST /v1/collections/{id}/documents/{file_id}) as documented. - Collections gained
update(PUT),listDocuments,document,documents(:batchGet), andregenerateIndices(PATCH), and every management call takesteamID:plus paging and filter parameters. - New
XaiModelsClientfor/v1/modelsand the richerlanguage-models,image-generation-models, andvideo-generation-modelscatalogs. - New
XaiPlatformClient:apiKeyInfo(),tokenizeText, SIP phone numbers (/v2/phone-numbers),referCall/hangUpCall, and the TTS voice and custom-voice catalogs. XaiBatchClientgainedaddRequestsandcancel;XaiFilesClientgained list paging/filtering andupdate;XaiModelgainedretrieveResponseanddeleteResponse.
Amazon Bedrock
BedrockMantleProvidertargets Bedrock'sbedrock-mantleendpoint:responses(_:)andchat(_:)for the OpenAI-compatible surfaces andmessages(_:)for the Anthropic Messages surface, with Bedrock API-key auth.BedrockModelcontinues to servebedrock-runtimeand SigV4.
Meta
MetaModelruns Muse Spark on Meta Model API's Responses endpoint (MetaModel.chat(...)for chat completions). Key fromMODEL_API_KEY, base URLhttps://api.meta.ai/v1, and a 1M-token context window.MetaModel.Tools.webSearch(searchContextSize:userLocation:)and.toolSearch(...)are the server-side search-grounding and deferred tool-loading path; citations arrive asStreamPart.source.- Muse Spark always reasons, so
.noneis dropped rather than sent (the API answers it with a 400), and unlike OpenAI's reasoning models it still acceptstemperatureandtopP, so both are forwarded.
Fixes
- Bedrock silently dropped URL-only images and files. Models now declare what they can fetch, and the loop inlines the rest.
- A reused tool call id started a new UI tool part instead of overwriting the finished one.
- Cancelling during tool execution aborts the run rather than surfacing as a tool error.
- Tool results from resumed approvals appear in
stepsandresult.toolResults, not only inmessages.
Errors and utilities
- New
AIErrorcases:timedOut,invalidToolInput,invalidToolContext,missingToolResults,toolCallRepairFailed,invalidToolApproval,unsupportedFunctionality, andauthorizationRequired. JSONValuegained anIntsubscript, sovalue["input"]?[0]?["type"]works for array elements.
Docs
- A new API reference covering every public function and the
types you construct directly. Signatures are extracted from
Sources/AIon every build, so they cannot drift from the code. - New Foundations section for the ideas the rest of the docs used to assume: the loop, models and tokens, prompts and messages, tool calling, and streaming.
- New Troubleshooting section, one page per symptom, named after what you would actually search for.
- The catch-all Advanced page is gone, split into Context management, Middleware, Runtime context, Telemetry, and Errors and retries. Runtime context, telemetry, and history handling had been nested under Middleware, which is not what any of them are.
- New pages for the terminal UI and for timeouts and approvals, and the agent skill gained references for context management, the terminal UI, timeouts and approvals, and runtime context.
0.2.0
New providers
- Chat:
MoonshotModel(Kimi),AlibabaModel(Qwen, with native thinking,AlibabaEmbeddingModel, andAlibabaVideoModelfor Wan), andHuggingFaceModel(the router's Responses endpoint). - Retrieval:
VoyageEmbeddingModelandVoyageRerankingModel. - Voice:
CartesiaSpeechModelandCartesiaTranscriptionModel. - Images:
BlackForestLabsImageModel(FLUX),ByteDanceImageModel(Seedream),ProdiaImageModel, andQuiverAIImageModel(prompt-to-SVG). - Video:
ByteDanceVideoModel(Seedance) andKlingVideoModel(JWT-signed).
Provider capabilities
- xAI gained image, speech, and transcription packs, video
editVideo/extendVideo, deferred completions and response compaction, and theXaiFilesClient/XaiBatchClient/XaiCollectionsClientREST clients. Live Search (SearchParameters) is deprecated in favor of theweb_search/x_searchtools. - OpenAI: computer use (
OpenAIModel.Tools.computerUse) with thecomputer_call/computer_call_outputround-trip, hosted-tool calls and refusals now surface on the Responses stream, andOpenAIResponsesClientmanages stored/background responses (retrieve, delete, cancel, compact, input items, token counting). - Bedrock now signs with SigV4 when given IAM credentials (bearer-token auth still works).
- Groq server tools (
browserSearch,codeExecution) for the compound models. - Google grounding chunks surface as
.source; the full grounding metadata, OpenAI logprobs, Anthropic cache-creation tokens, Bedrock guardrail traces, and Perplexity images / related questions all collect onresult.providerMetadata.
MCP
MCPStdioTransportlaunches a local server as a subprocess and speaks newline-delimited JSON-RPC over its pipes;MCPSSETransportspeaks the legacy HTTP+SSE protocol. Both bound each call withrequestTimeout.MCPHTTPTransportcarriesmcp-session-idsessions, andtools()followsnextCursorpagination.fingerprintTools/detectToolDriftcatch a server that changes its tool definitions after you approved them (rug pull).
Core
smoothStreamre-chunks a text stream by word or line for calmer UI.generateObjectArrayreturns a typed array;repairTextsalvages unparseable JSON;output:ongenerateTextproduces a structured object alongside tool calls (result.experimentalOutput).repairToolCallfixes a malformed tool call before it runs; tools can return images throughTool.modelOutput(multimodal tool results).- New
streamTextcallbacksonChunkandonAbort;maxImagesPerCallbatches image generation; a.providerMetadatachannel runs through the whole stream.
Docs
- Examples and guides for every new provider and feature, a computer-use and a self-repair guide, and the agent skill refreshed to match.
0.1.1
Providers
- First-class model packs for AI Gateway, Baseten, Cerebras, DeepInfra,
Fireworks, LM Studio, Ollama, OpenRouter, Sarvam, Together AI, and Vercel.
Dedicated types (
BasetenModel,CerebrasModel, and so on) built on a shared OpenAI-compatible base, replacing theOpenAICompatibleProviderfactory functions for these providers (still available, deprecated).MistralModel,PerplexityModel,DeepSeekModel, andGroqModelmoved onto the same shared base for consistency, and every pack listed here now acceptsqueryParams. - Together AI, DeepInfra, and Baseten also get dedicated embedding model
types:
TogetherAIEmbeddingModel,DeepInfraEmbeddingModel, andBasetenEmbeddingModel. - OpenRouter's reasoning effort now maps to its actual nested
reasoning: {"effort": ...}wire format instead of the genericreasoning_effortfield other OpenAI-compatible providers use.
Examples
- Reorganized into
Examples/Features/(the same numbered walkthroughs as before, plus a new 23-WorkflowGuides) andExamples/Providers/<Name>, a minimal runnable example for every supported provider.
0.1.0
The first release. A Swift port of the Vercel AI SDK for iOS and macOS.
Core
generateTextandstreamText, with the tool-calling loop, steps, and streamed reasoning.- Structured output:
generateObject,streamObject(pluselementStreamfor arrays),generateEnum, andgenerateJSON. embed,embedMany,cosineSimilarity, andrerank.- A
SchemaDSL that validates arguments and output before decoding. ReasoningEffortmaps to each provider's native reasoning controls; reasoning streams as.reasoningDelta.
Agents and tools
Agent, theToolLoopAgentanalog: a model bundled with instructions, tools, and loop settings. Also works as aChatTransport.- Loop control (
stopWhen,stepCountIs,hasToolCall), plusprepareCall,prepareStep, andtoolOrder. - Closure-based
Toolwith typed arguments, execution context, approvals, and client-side tools. - Subagents: any
Agentbecomes a tool viaasTool. - Provider-defined (server-executed) tools with typed builders under
<Model>.Toolsfor xAI, OpenAI, Google, and Anthropic: web and X search, code execution, file search, computer use, and more. Calls and results come back as provider-executed.toolCall/.toolResultparts, and Anthropic's required beta headers are added for you. - MCP tools over HTTP via
MCPClient.
Providers
Native packs that speak each provider's own wire:
OpenAIModel(Responses and.chat),AnthropicModel,GoogleModel,GoogleVertexModel,AzureOpenAIProvider,BedrockModel,XaiModel(with typedSearchParameterslive search),GroqModel,DeepSeekModel,MistralModel,PerplexityModel,CohereModel.OpenAICompatibleProviderfactories for Together, Fireworks, Cerebras, OpenRouter, DeepInfra, Baseten, Vercel, Gateway, Ollama, LM Studio, and Sarvam.- Sarvam:
sarvam-30b/sarvam-105breasoning chat,SarvamSpeechModel(Bulbul), andSarvamTranscriptionModel(Saaras) for Indian languages. ProviderRegistryandcustomProviderfor"provider:model"strings and aliases.
Middleware
wrapLanguageModelwithextractReasoning,simulateStreaming,defaultSettings, andcache(backed byLanguageModelCache; ships an in-processInMemoryLanguageModelCache).- Hooks:
transformRequest,wrapStream, andwrapCall(wrap the whole call and decide whether to run the model).
Media
- Images: OpenAI, fal, Luma, Replicate.
- Speech: OpenAI, ElevenLabs, LMNT, Hume, Deepgram, Sarvam.
- Transcription: OpenAI, ElevenLabs, Deepgram, AssemblyAI, Rev.ai, Gladia, Sarvam.
- Video: xAI, Luma.
UI and realtime
ChatSession,CompletionSession, andObjectSessionas@Observableobjects for SwiftUI.- The UI-message stream protocol, wire-compatible with the AI SDK's
/api/chatroute:ChatTransport,HTTPChatTransport,LocalChatTransport,readUIMessageStream, message metadata, and stream resumption. - Realtime voice over WebSockets (OpenAI, Google (Gemini Live), and xAI)
through
RealtimeSession.
On-device
FoundationModelsModelruns Apple Intelligence through the same API as the cloud providers, with nothing leaving the device.
Tooling
AITelemetryspans, structuredAIError, and testing helpers in theAITestingmodule.