### Environment Setup Source: https://github.com/teunlao/swift-ai-sdk/blob/main/examples/README.md Instructions for setting up the environment by copying the example .env file and adding necessary API keys. ```bash cp .env.example .env # edit .env and add OPENAI_API_KEY / ANTHROPIC_API_KEY / ... ``` -------------------------------- ### Register New Example Source: https://github.com/teunlao/swift-ai-sdk/blob/main/examples/README.md Example of how to register a new Swift example within the ExampleCatalog, ensuring it's accessible via the CLI. ```swift ExampleCatalog.register(GenerateTextBasic.self, path: GenerateTextBasic.name) ``` -------------------------------- ### List Registered Examples Source: https://github.com/teunlao/swift-ai-sdk/blob/main/examples/README.md Command to list all currently registered examples using the Swift Package Manager CLI. ```bash cd examples swift run AICoreExamples --list ``` -------------------------------- ### Start the MCP Server Source: https://github.com/teunlao/swift-ai-sdk/blob/main/tools/orchestrator-mcp/README.md Starts the main Orchestrator MCP server process. Ensure dependencies are installed and the project is built. ```bash npm start ``` -------------------------------- ### Run Specific Example Source: https://github.com/teunlao/swift-ai-sdk/blob/main/examples/README.md Command to run a specific example by its upstream-like path using the Swift Package Manager CLI. ```bash swift run AICoreExamples tools/weather-tool ``` -------------------------------- ### Project Directory Structure Source: https://github.com/teunlao/swift-ai-sdk/blob/main/examples/README.md Illustrates the layout of the Swift AI SDK examples directory, including shared core components and AI core examples. ```bash examples/ ├── Sources/ │ ├── ExamplesCore/ # Shared logging/env helpers + example registry │ └── AICoreExamples/ # Swift ports of `external/vercel-ai-sdk/examples/ai-core/src` │ ├── ExampleIndex.swift # Registers all available examples with the CLI │ ├── Main.swift # CLI entry point (list + run by path) │ └── Tools/ │ └── WeatherTool.swift └── Package.swift # SwiftPM manifest (other legacy targets are being migrated here) ``` -------------------------------- ### Using System Prompts for Travel Itinerary Planning Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/foundations/prompts.mdx Set an initial system prompt to guide the model's behavior. This example uses the `system` property to instruct the model to act as a travel planner. ```swift import SwiftAISDK import OpenAIProvider let destination = "Kyoto" let lengthOfStay = 5 let result = try await generateText( model: openai("gpt-4o"), system: "You help planning travel itineraries. Respond to the users request with a list of the best stops to make in their destination.", prompt: "I am planning a trip to \(destination) for \(lengthOfStay) days. " + "Please suggest the best tourist activities for me to do." ) print(result.text) ``` -------------------------------- ### Install and Build Orchestrator MCP Source: https://github.com/teunlao/swift-ai-sdk/blob/main/tools/orchestrator-mcp/README.md Installs dependencies and builds the Orchestrator MCP project. Navigate to the project directory first. ```bash cd tools/orchestrator-mcp npm install npm run build ``` -------------------------------- ### Quickstart: Streaming Text Generation with OpenAI Source: https://github.com/teunlao/swift-ai-sdk/blob/main/README.md Demonstrates minimal text generation and streaming using the OpenAI provider. Ensure the OPENAI_API_KEY environment variable is set. ```swift import SwiftAISDK import OpenAIProvider @main struct Demo { static func main() async throws { // Set OPENAI_API_KEY in your environment (loaded lazily by the provider). // Streaming text let stream = try streamText( model: openai("gpt-5"), prompt: "Stream one sentence about structured outputs." ) for try await delta in stream.textStream { print(delta, terminator: "") } } } ``` -------------------------------- ### Create Language Model Instance Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/alibaba.mdx Instantiate a language model using the Alibaba provider. This is the basic setup for generating text. ```swift import SwiftAISDK import AlibabaProvider let result = try await generateText( model: alibaba("qwen-plus"), prompt: "Write a vegetarian lasagna recipe for 4 people." ) print(result.text) ``` -------------------------------- ### Swift Package Manager Setup for Replicate Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/replicate.mdx Add the Swift AI SDK and Replicate provider to your project using Swift Package Manager. ```swift // Package.swift (excerpt) dependencies: [ .package(url: "https://github.com/teunlao/swift-ai-sdk", from: "0.17.6") ], targets: [ .target( name: "YourTarget", dependencies: [ .product(name: "SwiftAISDK", package: "swift-ai-sdk"), .product(name: "ReplicateProvider", package: "swift-ai-sdk") ] ) ] ``` -------------------------------- ### Configure Prodia Provider Options Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/prodia.mdx Example demonstrating how to set specific Prodia provider options like width, height, steps, and style preset for image generation. ```swift let result = try await generateImage( model: prodia.image("inference.flux-fast.schnell.txt2img.v2"), prompt: "A cat wearing an intricate robe", providerOptions: [ "prodia": [ "width": 1024, "height": 768, "steps": 4, "stylePreset": "cinematic" ] ] ) ``` -------------------------------- ### Unified Provider Architecture Example Source: https://github.com/teunlao/swift-ai-sdk/blob/main/README.md Illustrates how to switch between different AI providers (OpenAI, Anthropic, Google) without altering the function signature for text generation. The model list can be configured with specific provider models. ```swift import SwiftAISDK import OpenAIProvider import AnthropicProvider import GoogleProvider let models: [LanguageModel] = [ openai("gpt-5"), anthropic("claude-4.5-sonnet"), google("gemini-2.5-pro") ] for model in models { let result = try await generateText( model: model, prompt: "Invent a new holiday and describe its traditions." ) print(result.text) } ``` -------------------------------- ### Using System Messages for Guidance Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/foundations/prompts.mdx Illustrates how to use system messages to guide the assistant's behavior before user messages are processed. This is an alternative to using the `system` property directly. ```swift import SwiftAISDK import OpenAIProvider let result = try await generateText( model: openai("gpt-4o"), messages: [ .system(SystemModelMessage(content: "You help planning travel itineraries.")), .user(UserModelMessage(content: .text("I am planning a trip to Berlin for 3 days. Please suggest the best tourist activities for me to do."))) ] ) ``` -------------------------------- ### Generate Image with Model-Specific Options Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/replicate.mdx Shows how to pass model-specific options to Replicate for image generation, using 'style' as an example. Requires the 'replicate' key in providerOptions. ```swift let result = try await generateImage( model: replicate.image("recraft-ai/recraft-v3"), prompt: "The Loch Ness Monster getting a manicure", size: "1365x1024", providerOptions: [ "replicate": ["style": .string("realistic_image")] ] ) ``` -------------------------------- ### Provide Tool Usage Instructions for Research Agent Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/agents/building-agents.mdx Guide an agent on how to effectively use available tools like web search and document analysis for research tasks. ```swift let researchAgent = Agent(settings: .init( model: .v3(openai("gpt-4o")), system: """ You are a research assistant with access to search and document tools. When researching: 1. Always start with a broad search to understand the topic 2. Use document analysis for detailed information 3. Cross-reference multiple sources before drawing conclusions 4. Cite your sources when presenting information 5. If information conflicts, present both viewpoints """, tools: [ "webSearch": webSearch, "analyzeDocument": analyzeDocument, "extractQuotes": extractQuotes ] )) ``` -------------------------------- ### Swift Package Manager Installation Source: https://github.com/teunlao/swift-ai-sdk/blob/main/README.md Add the Swift AI SDK to your project's Package.swift file. Ensure you use the latest release tag for the package version. ```swift // Package.swift dependencies: [ // Use the latest release tag (e.g. "0.17.6"). .package(url: "https://github.com/teunlao/swift-ai-sdk.git", from: "0.17.6") ], targets: [ .target( name: "YourApp", dependencies: [ .product(name: "SwiftAISDK", package: "swift-ai-sdk"), .product(name: "OpenAIProvider", package: "swift-ai-sdk") ] ) ] ``` -------------------------------- ### Setup Provider Registry with Multiple Providers Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/ai-sdk-core/provider-management.mdx Create a provider registry by registering multiple AI providers like Anthropic and OpenAI. Ensure necessary environment variables like OPENAI_API_KEY are set. ```swift import SwiftAISDK import AnthropicProvider import OpenAIProvider let registry = createProviderRegistry( providers: [ // Register provider with prefix: "anthropic": anthropic, // Register provider with custom configuration: "openai": createOpenAI( apiKey: ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ) ] ) ``` -------------------------------- ### LMNT Provider Setup with Swift Package Manager Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/lmnt.mdx Configure your project to include the Swift AI SDK and the LMNT provider using Swift Package Manager. ```swift // Package.swift (excerpt) dependencies: [ .package(url: "https://github.com/teunlao/swift-ai-sdk", from: "0.17.6") ], targets: [ .target( name: "YourTarget", dependencies: [ .product(name: "SwiftAISDK", package: "swift-ai-sdk"), .product(name: "LMNTProvider", package: "swift-ai-sdk") ] ) ] ``` -------------------------------- ### Create a Simple Calculator Tool Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/zod-adapter/overview.mdx Defines a tool for basic arithmetic operations using Zod for input schema validation. This example demonstrates how to integrate a tool with the Swift AI SDK for text generation. ```swift import SwiftAISDK import OpenAIProvider import AISDKProviderUtils import AISDKZodAdapter let calculator = tool( description: "Perform basic arithmetic operations", inputSchema: flexibleSchemaFromZod3(z.object([ "operation": z.string(), // "add", "subtract", "multiply", "divide" "a": z.number(), "b": z.number() ])), execute: { input, _ in guard case .object(let obj) = input, case .string(let op) = obj["operation"] ?? .null, case .number(let a) = obj["a"] ?? .null, case .number(let b) = obj["b"] ?? .null else { return .value(.string("Invalid input")) } let result: Double switch op { case "add": result = a + b case "subtract": result = a - b case "multiply": result = a * b case "divide": result = b != 0 ? a / b : 0 default: return .value(.string("Unknown operation")) } return .value(.number(result)) } ) // Use the tool let result = try await generateText( model: openai("gpt-4o"), tools: ["calculator": calculator], prompt: "What is 234 multiplied by 89? Use the calculator tool." ) print(result.text) // Output: The result of 234 multiplied by 89 is 20,826. ``` -------------------------------- ### Swift Logging Middleware Example Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/ai-sdk-core/middleware.mdx Implements middleware to log parameters and generated text for both generate and stream operations. Useful for debugging and understanding model interactions. ```swift import Foundation import AISDKProvider func yourLogMiddleware() -> LanguageModelV3Middleware { LanguageModelV3Middleware( wrapGenerate: { doGenerate, _, params, _ in print("doGenerate called") print("params: \(params)") let result = try await doGenerate() print("doGenerate finished") // Collect text from content let text = result.content.compactMap { content -> String? in if case .text(let textPart) = content { return textPart.text } return nil }.joined() print("generated text: \(text)") return result }, wrapStream: { _, doStream, params, _ in print("doStream called") print("params: \(params)") let result = try await doStream() var generatedText = "" var textBlocks: [String: String] = [:] let transformedStream = AsyncThrowingStream { continuation in Task { do { for try await chunk in result.stream { switch chunk { case .textStart(let id, _): textBlocks[id] = "" case .textDelta(let id, let delta, _): let existing = textBlocks[id] ?? "" textBlocks[id] = existing + delta generatedText += delta case .textEnd(let id, _): print("Text block \(id) completed: \(textBlocks[id] ?? "")") default: break } continuation.yield(chunk) } print("doStream finished") print("generated text: \(generatedText)") continuation.finish() } catch { continuation.finish(throwing: error) } } } return LanguageModelV3StreamResult( stream: transformedStream, request: result.request, response: result.response ) } ) } ``` -------------------------------- ### Structured Output Generation with OpenAI Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/openai.mdx Illustrates how to generate structured data, like JSON objects conforming to a schema, using OpenAI models. This example uses `generateObject` with a Codable struct. ```swift // Using generateObject import SwiftAISDK import OpenAIProvider struct Ingredient: Codable, Sendable { let name: String; let amount: String } struct Recipe: Codable, Sendable { let name: String let ingredients: [Ingredient] let steps: [String] } let result = try await generateObject( model: openai("gpt-4.1"), schema: Recipe.self, prompt: "Generate a lasagna recipe.", schemaName: "recipe", schemaDescription: "A recipe for lasagna." ).object ``` -------------------------------- ### Implement Main Application Logic Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/getting-started/cli-quickstart.mdx Sets up the main entry point for the command-line application, handling user prompts and streaming AI responses. ```swift import Foundation import SwiftAISDK import OpenAIProvider @main struct App { static func main() async { let prompt = CommandLine.arguments.dropFirst().joined(separator: " ") guard !prompt.isEmpty else { print("Usage: aicli ") return } do { let stream = try streamText(model: openai("gpt-4o"), prompt: prompt) for try await delta in stream.textStream { print(delta, terminator: "") } print() } catch { fputs("Error: \(error)\n", stderr) } } } ``` -------------------------------- ### Initialize Swift Package Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/getting-started/cli-quickstart.mdx Creates a new Swift executable package and navigates into its directory. ```bash swift package init --type executable --name aicli cd aicli ``` -------------------------------- ### Generate Video from Image and Text Prompt (Alibaba) Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/alibaba.mdx This example demonstrates generating a video from an initial image and an optional text prompt using Alibaba's 'wan2.6-i2v' model. It shows how to load image data and set a poll timeout. ```swift import SwiftAISDK import AlibabaProvider import AISDKProviderUtils import Foundation let imageData = try Data(contentsOf: URL(string: "https://example.com/landscape.jpg")!) let result = try await experimental_generateVideo( model: alibaba.video("wan2.6-i2v"), prompt: .imageToVideo( image: .data(imageData), text: "Camera slowly pans across the landscape" ), duration: 5, providerOptions: [ "alibaba": [ "pollTimeoutMs": 600_000 // 10 minutes ] ] ) try result.video.data.write(to: URL(fileURLWithPath: "video.mp4")) ``` -------------------------------- ### Generate Video from First-Frame Image Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/bytedance.mdx Generate a video starting with a provided image and an optional text prompt. This is useful for creating videos that evolve from a specific visual starting point. Ensure ByteDanceProvider is imported. ```swift import SwiftAISDK import ByteDanceProvider import Foundation let result = try await experimental_generateVideo( model: byteDance.video("seedance-1-5-pro-251215"), prompt: .imageToVideo( image: .string("https://example.com/first-frame.png"), text: "The cat slowly turns its head and blinks" ), duration: 5, providerOptions: ["bytedance": [ "watermark": false ]] ) try result.video.data.write(to: URL(fileURLWithPath: "video.mp4")) ``` -------------------------------- ### Specify Image Size Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/prodia.mdx Example of generating an image with a custom size specified in WIDTHxHEIGHT format. ```swift let result = try await generateImage( model: prodia.image("inference.flux-fast.schnell.txt2img.v2"), prompt: "A serene mountain landscape at sunset", size: "1024x768" ) ``` -------------------------------- ### Generate Image with Provider Options Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/togetherai.mdx Example of generating an image with custom provider-specific options for TogetherAI, such as generation steps. ```swift let result = try await generateImage( model: togetherai.image("black-forest-labs/FLUX.1-dev"), prompt: "A delighted resplendent quetzal mid flight amidst raindrops", size: "512x512", providerOptions: [ "togetherai": [ "steps": 40 ] ] ) ``` -------------------------------- ### Initialize a Basic Agent Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/agents/building-agents.mdx Instantiate the Swift Agent with basic settings including model and system prompt. This is the foundational step for creating an agent. ```swift import SwiftAISDK import OpenAIProvider let myAgent = Agent(settings: .init( model: .v3(openai("gpt-4o")), system: "You are a helpful assistant.", tools: [:] )) ``` -------------------------------- ### Access Prodia Provider Metadata Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/prodia.mdx Example of retrieving and printing the Job ID from the provider-specific metadata returned by Prodia. ```swift import SwiftAISDK import ProdiaProvider let result = try await generateImage( model: prodia.image("inference.flux-fast.schnell.txt2img.v2"), prompt: "A serene mountain landscape at sunset" ) if let first = result.providerMetadata["prodia"]?.images.first, case let .object(fields) = first, case let .string(jobId)? = fields["jobId"] { print("Job ID:", jobId) } ``` -------------------------------- ### Audio Input with OpenAI's gpt-4o-audio-preview Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/openai.mdx Illustrates how to pass audio files to the `gpt-4o-audio-preview` model for processing. This model requires audio inputs and is currently in preview. ```swift import SwiftAISDK import OpenAIProvider let result = try await generateText( model: openai.chat("gpt-4o-audio-preview"), messages: [ [ "role": "user", "content": [ ["type": "text", "text": "What is the audio saying?"], [ "type": "file", "mediaType": "audio/mpeg", "data": try Data(contentsOf: URL(fileURLWithPath: "./data/galileo.mp3")) ] ] ] ] ) ``` -------------------------------- ### Create Rev.ai Transcription Model Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/revai.mdx Instantiate a Rev.ai transcription model using its ID. This is the basic setup for transcription. ```swift import RevAIProvider let model = revai.transcription("machine") ``` -------------------------------- ### Generate Image with TogetherAI Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/togetherai.mdx Basic example of generating an image using a TogetherAI model. Ensure you have imported SwiftAISDK and TogetherAIProvider. ```swift import SwiftAISDK import TogetherAIProvider let result = try await generateImage( model: togetherai.image("black-forest-labs/FLUX.1-dev"), prompt: "A delighted resplendent quetzal mid flight amidst raindrops" ) try result.image.data.write(to: URL(fileURLWithPath: "image.png")) ``` -------------------------------- ### Define Anthropic Bash Tool Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/anthropic.mdx Example of how to define and use the Anthropic Bash Tool, specifying the command execution logic. ```swift let bashTool = anthropic.tools.bash_20241022( execute: { command, restart in // Implement your bash command execution logic here // Return the result of the command execution } ) ``` -------------------------------- ### Sequential Processing with Swift Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/agents/workflows.mdx Demonstrates sequential processing by generating marketing copy and then evaluating its quality. If the quality is insufficient, it re-generates the copy. Requires SwiftAISDK and OpenAIProvider. ```swift import SwiftAISDK import OpenAIProvider struct MarketingQuality: Codable, Sendable { let hasCallToAction: Bool let emotionalAppeal: Int let clarity: Int } struct MarketingResult: Sendable { let copy: String let quality: MarketingQuality } func generateMarketingCopy(_ input: String) async throws -> MarketingResult { let copy = try await generateText( model: openai("gpt-4o"), prompt: "Write persuasive marketing copy for: \(input). Focus on benefits and emotional appeal." ).text let quality = try await generateText( model: openai("gpt-4o"), experimentalOutput: Output.object(MarketingQuality.self, name: "quality_check"), prompt: """Evaluate this marketing copy for: 1. Presence of call to action (true/false) 2. Emotional appeal (1-10) 3. Clarity (1-10) Copy to evaluate: \(copy) """ ).experimentalOutput if !quality.hasCallToAction || quality.emotionalAppeal < 7 || quality.clarity < 7 { let improved = try await generateText( model: openai("gpt-4o"), prompt: "Rewrite this marketing copy with a clear CTA, stronger emotional appeal, and improved clarity. Original: \(copy)" ) return .init(copy: improved.text, quality: quality) } return .init(copy: copy, quality: quality) } ``` -------------------------------- ### Generate Image with Seed for Reproducibility Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/prodia.mdx Example of generating an image using a specific seed value to ensure reproducible results. ```swift let result = try await generateImage( model: prodia.image("inference.flux-fast.schnell.txt2img.v2"), prompt: "A serene mountain landscape at sunset", seed: 12345 ) ``` -------------------------------- ### Access Fal Provider Metadata Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/fal.mdx Example of accessing provider-specific metadata returned with the image generation result, specifically for Fal. ```swift if let first = result.providerMetadata["fal"]?.images.first { print(first) // JSONValue (provider-specific) } ``` -------------------------------- ### Import Default Alibaba Provider Instance Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/alibaba.mdx Import the default `alibaba` provider instance for easy access to Qwen models. ```swift import AlibabaProvider let model = alibaba("qwen-plus") ``` -------------------------------- ### Generate Image with Prodia Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/prodia.mdx Basic example of generating an image using a Prodia model and saving it. Requires SwiftAISDK and ProdiaProvider imports. ```swift import SwiftAISDK import ProdiaProvider let result = try await generateImage( model: prodia.image("inference.flux-fast.schnell.txt2img.v2"), prompt: "A cat wearing an intricate robe" ) try result.image.data.write(to: URL(fileURLWithPath: "image.png")) ``` -------------------------------- ### Initialize Web Search Tool with Custom Configuration Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/anthropic.mdx Initializes the Web Search Tool with custom configuration, including maximum uses, allowed and blocked domains, and user location for geographically relevant results. ```swift let webSearchTool = anthropic.tools.webSearch_20250305( maxUses: 3, allowedDomains: ["techcrunch.com", "wired.com"], blockedDomains: ["example-spam-site.com"], userLocation: [ "type": "approximate", "country": "US", "region": "California", "city": "San Francisco", "timezone": "America/Los_Angeles" ] ) let result = try await generateText( model: anthropic("claude-opus-4-20250514"), prompt: "Find local news about technology", tools: [ "web_search": webSearchTool ] ) ``` -------------------------------- ### Initialize Web Search Tool with Default Settings Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/anthropic.mdx Initializes the Web Search Tool with default settings, allowing it to be used in text generation. ```swift import SwiftAISDK import AnthropicProvider let webSearchTool = anthropic.tools.webSearch_20250305( maxUses: 5 ) let result = try await generateText( model: anthropic("claude-opus-4-20250514"), prompt: "What are the latest developments in AI?", tools: [ "web_search": webSearchTool ] ) ``` -------------------------------- ### Generate Text with Mistral Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/mistral.mdx Use the `generateText` function to get text completions from Mistral models. Ensure you import SwiftAISDK and MistralProvider. ```swift import SwiftAISDK import MistralProvider let result = try await generateText( model: mistral("mistral-large-latest"), prompt: "Write a vegetarian lasagna recipe for 4 people." ) let text = result.text ``` -------------------------------- ### Build Consolidated Executable Source: https://github.com/teunlao/swift-ai-sdk/blob/main/examples/README.md Command to build the consolidated AICoreExamples executable using Swift Package Manager. ```bash cd examples swift build --target AICoreExamples ``` -------------------------------- ### Tool Calling with OpenAI Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/getting-started/navigating-the-library.mdx This snippet shows how to enable tool calling for an OpenAI model, defining a tool to get weather information. ```swift let result = try await generateText( model: openai("gpt-4o"), tools: [ "getWeather": tool( description: "Get weather for a location", parameters: z.object(["location": z.string()]) ) { args in return "Sunny, 72°F" } ], prompt: "What's the weather in San Francisco?" ) ``` -------------------------------- ### Import and Use Alibaba Provider Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/foundations/providers-and-models.mdx Import the Alibaba provider module and use the global shortcut to instantiate a model. API keys are loaded from environment variables. ```swift import AlibabaProvider // Use the global shortcut for Alibaba models let alibaba = alibaba("qwen-plus") ``` -------------------------------- ### Zod-like DSL Schema Definition Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/zod-adapter/overview.mdx Example of defining the same tool schema using the Zod-like DSL. This approach offers a cleaner and more readable syntax. ```swift import AISDKProviderUtils import AISDKZodAdapter let weatherTool = tool( description: "Get current weather", inputSchema: flexibleSchemaFromZod3(z.object([ "location": z.string(), "units": z.optional(z.string()) ])), execute: { input, _ in // Execute weather API call return .value(.string("22°C, sunny")) } ) ``` -------------------------------- ### Manual JSON Schema Definition Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/zod-adapter/overview.mdx Example of defining a tool schema using manual JSON Schema. This approach is verbose and prone to errors. ```swift import AISDKProviderUtils let weatherTool = tool( description: "Get current weather", inputSchema: FlexibleSchema(jsonSchema( .object([ "type": .string("object"), "properties": .object([ "location": .object([ "type": .string("string"), "description": .string("City name") ]), "units": .object([ "type": .string("string"), "enum": .array([.string("celsius"), .string("fahrenheit")]), "description": .string("Temperature units") ]) ]), "required": .array([.string("location")]), "additionalProperties": .bool(false) ]) )), execute: { input, _ in // Execute weather API call return .value(.string("22°C, sunny")) } ) ``` -------------------------------- ### Send Base-64 Encoded Image in Prompt Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/foundations/prompts.mdx This example shows how to send a base64 encoded image string. It requires SwiftAISDK, OpenAIProvider, and Foundation. ```swift import SwiftAISDK import OpenAIProvider import Foundation let base64 = try Data(contentsOf: URL(fileURLWithPath: "./data/comic-cat.png")).base64EncodedString() let result = try await generateText( model: openai("gpt-4o"), messages: [ .user(UserModelMessage(content: .parts([ .text(TextPart(text: "Describe the image in detail.")), .image(ImagePart(image: .string(base64))) ]))) ] ) print(result.text) ``` -------------------------------- ### Analyze Game Results in Python Source: https://github.com/teunlao/swift-ai-sdk/blob/main/Tests/AnthropicProviderTests/Fixtures/anthropic-programmatic-tool-calling.1.chunks.txt Provides an analysis of the game, starting with the total number of rounds played. This snippet is useful for post-game statistics. ```python # Determine who was cheating based on the results print("\n📊 Analysis:") print(f"Total rounds played: {round_num}") ``` -------------------------------- ### Import and Use OpenAI Provider Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/foundations/providers-and-models.mdx Import the OpenAI provider module and use the global shortcut to instantiate a model. API keys are loaded from environment variables. ```swift import OpenAIProvider // Use the global shortcut for OpenAI models let openai = openai("gpt-4o") ``` -------------------------------- ### Define Agent Role and Expertise Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/agents/building-agents.mdx Set the agent's fundamental role and area of expertise. This is a basic starting point for agent behavior. ```swift let agent = Agent(settings: .init( model: .v3(openai("gpt-4o")), system: "You are an expert data analyst. You provide clear insights from complex data." )) ``` -------------------------------- ### Generate Text with Anthropic Model Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/anthropic.mdx Use the `generateText` function to get a text response from an Anthropic model. Ensure you import SwiftAISDK and AnthropicProvider. ```swift import SwiftAISDK import AnthropicProvider let result = try await generateText( model: anthropic("claude-3-haiku-20240307"), prompt: "Write a vegetarian lasagna recipe for 4 people." ) let text = result.text ``` -------------------------------- ### Applying Middleware to a Provider Registry Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/ai-sdk-core/provider-management.mdx Demonstrates how to create a provider registry and apply middleware, such as reasoning extraction, to all language models accessed through it. This is useful for enforcing consistent behavior across models. ```swift import SwiftAISDK import OpenAIProvider let registry = createProviderRegistry( providers: [ "openai": openai ], options: ProviderRegistryOptions( languageModelMiddleware: .single( extractReasoningMiddleware( options: ExtractReasoningOptions(tagName: "think") ) ) ) ) // All language models from this registry will have reasoning extraction enabled let result = try await generateText( model: registry.languageModel(id: "openai:gpt-4o"), prompt: "Think step by step and wrap reasoning in tags" ) ``` -------------------------------- ### Configure Image Generation Options Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/google-generative-ai.mdx Customize image generation by passing provider-specific options, such as `personGeneration`, to the `providerOptions` parameter. This example disables person generation. ```swift import SwiftAISDK import GoogleProvider let result = try await generateImage( model: google.image("imagen-3.0-generate-002"), providerOptions: [ "google": [ "personGeneration": "dont_allow" ] ] // ... ) let image = result.image ``` -------------------------------- ### Initialize Computer Tool Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/anthropic.mdx Initializes the Computer Tool for simulating computer actions. The `execute` closure defines the logic for each action, and `toModelOutput` maps the result for LLM consumption. ```swift let computerTool = anthropic.tools.computer_20241022( displayWidthPx: 1920, displayHeightPx: 1080, displayNumber: 0, // Optional, for X11 environments execute: { action, coordinate, text in // Implement your computer control logic here // Return the result of the action // Example code: switch action { case "screenshot": // multipart result: return [ "type": "image", "data": try Data(contentsOf: URL(fileURLWithPath: "./data/screenshot-editor.png")).base64EncodedString() ] default: print("Action:", action) print("Coordinate:", coordinate as Any) print("Text:", text as Any) return "executed \(action)" } }, // map to tool result content for LLM consumption: toModelOutput: { result in if let stringResult = result as? String { return [["type": "text", "text": stringResult]] } else if let dictResult = result as? [String: Any], let data = dictResult["data"] { return [["type": "image", "data": data, "mediaType": "image/png"]] } return [] } ) ``` -------------------------------- ### Configuring Provider Options at Message Level Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/foundations/prompts.mdx Apply provider options granularly to individual messages. This example sets 'cacheControl' for an Anthropic system message. ```swift import SwiftAISDK let messages: [ModelMessage] = [ .system(SystemModelMessage( content: "Cached system message", providerOptions: [ // Sets a cache control breakpoint on the system message "anthropic": [ "cacheControl": .object(["type": .string("ephemeral")]) ] ] )) ] ``` -------------------------------- ### Create and Configure Tools Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/ai-sdk-core/tools-and-tool-calling.mdx Use the `tool` helper function to create tools with descriptions and input schemas. The `tool` function returns a `Tool` that can be added to a `ToolSet` for use with AI models. ```swift let greetTool = tool( description: "Greets the user", inputSchema: GreetingInput.self ) { input, _ in GreetingOutput(greeting: "Hello, \(input.name)!") } let ageTool = tool( description: "Tells the user their age", inputSchema: AgeInput.self ) { input, _ in AgeOutput(message: "You are \(input.age) years old!") } ``` -------------------------------- ### Basic Text Generation in Swift Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/ai-sdk-core/overview.mdx Demonstrates how to perform basic text generation using the AI SDK Core with an OpenAI model. Ensure you have imported SwiftAISDK and the relevant provider. ```swift import SwiftAISDK import OpenAIProvider let result = try await generateText( model: openai("gpt-4o"), prompt: "Write a 1‑sentence product tagline for a time‑tracking app." ) print(result.text) ``` -------------------------------- ### Create a Mistral Chat Model Instance Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/mistral.mdx Instantiate a Mistral chat model using its ID. This is the basic setup for calling the Mistral chat API. ```swift let model = mistral("mistral-large-latest") ``` -------------------------------- ### Setup Provider Registry with Custom Separator Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/ai-sdk-core/provider-management.mdx Customize the separator used in model IDs within a provider registry. The default separator is ':', but it can be changed to any string, such as ' > '. ```swift import SwiftAISDK import AnthropicProvider import OpenAIProvider let customSeparatorRegistry = createProviderRegistry( providers: [ "anthropic": anthropic, "openai": openai ], options: ProviderRegistryOptions(separator: " > ") ) ``` -------------------------------- ### Generate Text with Open Responses Model Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/open-responses.mdx Use the generateText function with a language model created from the Open Responses provider to get a text response. ```swift import SwiftAISDK import OpenResponsesProvider let openResponses = createOpenResponses(options: OpenResponsesProviderSettings( url: "http://localhost:1234/v1/responses", name: "aProvider" )) let result = try await generateText( model: try openResponses.languageModel(modelId: "mistralai/ministral-3-14b-reasoning"), prompt: "Invent a new holiday and describe its traditions." ) print(result.text) ``` -------------------------------- ### Generate Text with Common Settings Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/ai-sdk-core/settings.mdx Demonstrates how to use common AI SDK settings like maxOutputTokens, temperature, and maxRetries when generating text. Ensure necessary providers and SDKs are imported. ```swift import SwiftAISDK import OpenAIProvider let result = try await generateText( model: openai("gpt-4.1"), settings: CallSettings( maxOutputTokens: 512, temperature: 0.3, maxRetries: 5 ), prompt: "Invent a new holiday and describe its traditions." ) ``` -------------------------------- ### Configure OpenAI Completion Model with Options Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/openai.mdx Pass model-specific settings as an options argument to the `doGenerate` method. This includes options like echo, logitBias, suffix, and user. ```swift let model = openai.completion("gpt-3.5-turbo-instruct") try await model.doGenerate( providerOptions: [ "openai": [ "echo": true, // optional, echo the prompt in addition to the completion "logitBias": [ // optional likelihood for specific tokens "50256": -100 ], "suffix": "some text", // optional suffix that comes after a completion of inserted text "user": "test-user" // optional unique user identifier ] ] ) ``` -------------------------------- ### Configuring Provider Options at Function Call Level Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/foundations/prompts.mdx Pass provider-specific options directly to the function call for general configuration. This example sets 'reasoningEffort' for OpenAI. ```swift import SwiftAISDK import OpenAIProvider let result = try await generateText( model: openai("gpt-4o"), providerOptions: [ "openai": [ "reasoningEffort": .string("low") ] ] ) print(result.text) ``` -------------------------------- ### Create MCP Client with SSE Transport Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/ai-sdk-core/mcp-tools.mdx Initializes an MCP client using the recommended SSE transport. Ensure the URL and authorization token are correctly configured. ```swift import SwiftAISDK let client = try await createMCPClient( config: MCPClientConfig( transport: .config(MCPTransportConfig( type: "sse", // only "sse" is supported by the built-in factory url: "https://your-server.com/mcp", headers: ["Authorization": "Bearer YOUR_TOKEN"] )) ) ) ``` -------------------------------- ### Stream Text with Multiple Tools Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/foundations/tools.mdx Utilize streamText to handle streaming responses with multiple tools defined. This example shows how to include both 'getWeather' and 'countToThree' tools. ```swift let stream = try streamText( model: openai("gpt-4o"), tools: [ "getWeather": getWeather.eraseToTool(), "countToThree": countToThree.tool ], messages: [.user(UserModelMessage(content: .text("Count and tell weather")))] ) ``` -------------------------------- ### Build and Test Swift Project Source: https://github.com/teunlao/swift-ai-sdk/blob/main/CONTRIBUTING.md Run these commands to ensure your changes build and all tests pass locally before submitting a pull request. ```bash swift build && swift test ``` -------------------------------- ### Agent with Default Stop Condition Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/agents/loop-control.mdx Demonstrates setting up an agent with the default `stepCountIs(20)` stop condition explicitly. Ensure necessary imports are included. ```swift import SwiftAISDK import OpenAIProvider // Tool set defined elsewhere let toolset: ToolSet = [: ] let agent = Agent(settings: .init( model: openai("gpt-4o"), tools: toolset, // Default behaviour in Agent is stepCountIs(20), shown here explicitly stopWhen: [stepCountIs(20)] )) let result = try await agent.generate(prompt: .text( "Analyze this dataset and create a summary report" )) ``` -------------------------------- ### Set Timeout for Embedding Request Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/ai-sdk-core/embeddings.mdx Implement timeouts for embedding requests using the `abortSignal` closure. This example sets a timeout one second from the current date. ```swift import SwiftAISDK import OpenAIProvider let timeout = Date().addingTimeInterval(1) let embedding = try await embed( model: .v3(openai.textEmbeddingModel("text-embedding-3-small")), value: "sunny day at the beach", abortSignal: { Date() >= timeout } ) ``` -------------------------------- ### Generate Video from Text Prompt (Alibaba) Source: https://github.com/teunlao/swift-ai-sdk/blob/main/apps/docs/src/content/docs/providers/alibaba.mdx Use this snippet to generate videos from text descriptions using Alibaba's 'wan2.6-t2v' model. It includes options for prompt extension and setting a poll timeout for the asynchronous generation process. ```swift import SwiftAISDK import AlibabaProvider import Foundation let result = try await experimental_generateVideo( model: alibaba.video("wan2.6-t2v"), prompt: "A serene mountain lake at sunset with gentle ripples on the water.", resolution: "1280x720", duration: 5, providerOptions: [ "alibaba": [ "promptExtend": true, "pollTimeoutMs": 600_000 // 10 minutes ] ] ) try result.video.data.write(to: URL(fileURLWithPath: "video.mp4")) ```