### Build project with specific traits Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Use the swift build command to compile the project with the required backend traits. ```bash swift build --traits Claude,Response,Ollama,Metal ``` -------------------------------- ### Define and Use Tools with Tool Calling Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Shows how to define a custom tool using the Tool protocol and provide it to the LanguageModelSession for automatic execution. ```swift import OpenFoundationModels import OpenFoundationModelsMacros @Generable struct WeatherArguments { @Guide(description: "City name") var city: String } struct WeatherTool: Tool { var description: String { "Get current weather for a city" } func call(arguments: WeatherArguments) async throws -> String { return "Sunny, 24°C in \(arguments.city)" } } let session = LanguageModelSession( model: model, tools: [WeatherTool()], instructions: "You are a helpful assistant." ) let response = try await session.respond(to: "What's the weather in Tokyo?") // The session automatically executes the tool and returns the final answer ``` -------------------------------- ### Using Multiple Language Model Backends Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Demonstrates initializing and using Claude and Ollama models side-by-side within the same application using the LanguageModelSession. ```swift import ClaudeFoundationModels import OllamaFoundationModels let claude = ClaudeLanguageModel( configuration: ClaudeConfiguration(apiKey: "sk-..."), modelName: "claude-sonnet-4-5-20250929" ) let ollama = OllamaLanguageModel( configuration: OllamaConfiguration(), modelName: "llama3.2" ) // Use different models for different tasks let session1 = LanguageModelSession(model: claude, instructions: "You are a translator.") let session2 = LanguageModelSession(model: ollama, instructions: "You are a code reviewer.") async let translation = session1.respond(to: "Translate to Japanese: Hello") async let review = session2.respond(to: "Review this function: ...") ``` -------------------------------- ### Initialize Metal via swift-lm Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Loads a model using the Metal backend and performs a basic text generation request. ```swift import MetalFoundationModels import OpenFoundationModels let loader = MetalModelLoader() let container = try await loader.load(repo: "Qwen/Qwen2.5-0.5B-Instruct") let model = MetalLanguageModel(container: container) let session = LanguageModelSession(model: model) let response = try await session.respond(to: "Explain Swift concurrency briefly.") print(response.content) ``` -------------------------------- ### Initialize Claude Language Model Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Configures the Claude backend using an API key or environment variables. ```swift import ClaudeFoundationModels let config = ClaudeConfiguration(apiKey: "sk-...") // Or from environment: ClaudeConfiguration.fromEnvironment() let model = ClaudeLanguageModel( configuration: config, modelName: "claude-sonnet-4-5-20250929", thinkingBudgetTokens: 10000 // optional: enable extended thinking ) ``` -------------------------------- ### Initialize ClaudeLanguageModel for Text Generation Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Demonstrates how to configure and use a Claude language model to generate a text response. ```swift import OpenFoundationModels import ClaudeFoundationModels let model = ClaudeLanguageModel( configuration: ClaudeConfiguration(apiKey: "sk-..."), modelName: "claude-sonnet-4-5-20250929" ) let session = LanguageModelSession(model: model) let response = try await session.respond(to: "Explain quantum computing in one sentence.") print(response.content) ``` -------------------------------- ### Initialize Ollama Local Model Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Configures the local Ollama backend, which defaults to the local host and port. ```swift import OllamaFoundationModels let config = OllamaConfiguration() // defaults to http://127.0.0.1:11434, temperature: 0 let model = OllamaLanguageModel(configuration: config, modelName: "llama3.2") ``` -------------------------------- ### Initialize OpenAI Responses API Model Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Configures the OpenAI-compatible Responses backend. ```swift import ResponseFoundationModels let config = ResponseConfiguration(apiKey: "sk-...") let model = ResponseLanguageModel(configuration: config, model: "gpt-4.1") ``` -------------------------------- ### Initialize MLX Language Model Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Creates an MLX language model using a factory and a model descriptor. ```swift import MLXFoundationModels let factory = MLXLanguageModelFactory() let model = try await factory.makeLanguageModel( descriptor: .nanbeige41_3B_8bit ) ``` -------------------------------- ### Configure target dependencies with traits Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Enable specific backends using traits to keep the binary size small by only compiling necessary code. ```swift targets: [ .executableTarget( name: "MyApp", dependencies: [ .product(name: "OpenFoundationModels", package: "AnyFoundationModels"), .product(name: "ClaudeFoundationModels", package: "AnyFoundationModels", condition: .when(traits: ["Claude"])), .product(name: "ResponseFoundationModels", package: "AnyFoundationModels", condition: .when(traits: ["Response"])), .product(name: "OllamaFoundationModels", package: "AnyFoundationModels", condition: .when(traits: ["Ollama"])), .product(name: "MLXFoundationModels", package: "AnyFoundationModels", condition: .when(traits: ["MLX"])), .product(name: "MetalFoundationModels", package: "AnyFoundationModels", condition: .when(traits: ["Metal"])), ] ) ] ``` -------------------------------- ### Load Metal Model from Local Directory Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Loads a model from a local file system path using the Metal loader. ```swift let directory = URL(fileURLWithPath: "/path/to/local/model") let container = try await loader.load(directory: directory) let model = MetalLanguageModel(container: container, showsThinking: true) ``` -------------------------------- ### Stream Structured Output Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Shows how to stream structured data and collect the final parsed result. ```swift let stream = session.streamResponse( to: "Give me a recipe for miso soup", generating: Recipe.self ) for try await snapshot in stream { // snapshot.content is Recipe.PartiallyGenerated print(snapshot.content) } let final = try await stream.collect() print(final.content.name) // fully parsed Recipe ``` -------------------------------- ### Initialize Custom Hugging Face MLX Model Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Loads a custom Hugging Face model into the MLX backend using a specific model descriptor. ```swift let descriptor = MLXModelDescriptor( id: "mlx-community/your-model-4bit", promptStyle: .llama3 ) let model = try await factory.makeLanguageModel(descriptor: descriptor) ``` -------------------------------- ### Add AnyFoundationModels dependency to Package.swift Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Include the package in your Swift project dependencies. ```swift dependencies: [ .package(url: "https://github.com/1amageek/AnyFoundationModels.git", from: "0.5.6"), ] ``` -------------------------------- ### Stream Text Responses Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Demonstrates how to stream text content from a model response using an asynchronous loop. ```swift let stream = session.streamResponse(to: "Write a short story about a cat.") for try await snapshot in stream { print(snapshot.content, terminator: "") } ``` -------------------------------- ### Generate Structured Output with @Generable Source: https://github.com/1amageek/anyfoundationmodels/blob/main/README.md Uses the @Generable macro to define a Swift struct that the LLM will populate with structured data. ```swift import OpenFoundationModels import OpenFoundationModelsMacros @Generable struct Recipe { @Guide(description: "Name of the recipe") var name: String @Guide(description: "List of ingredients") var ingredients: [String] @Guide(description: "Step-by-step instructions") var steps: [String] @Guide(description: "Estimated cooking time in minutes") var cookingTimeMinutes: Int } let response = try await session.respond( to: "Give me a recipe for pancakes", generating: Recipe.self ) print(response.content.name) // "Classic Pancakes" print(response.content.ingredients) // ["flour", "eggs", ...] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.