LiteRT-LM の Swift API を使用すると、大規模言語モデルを iOS と macOS アプリケーションにネイティブに統合できます。マルチモーダリティ、ツール使用、GPU アクセラレーション(Metal 経由)などの機能は完全にサポートされています。
はじめに
Swift API を使用してモデルを初期化し、メッセージを送信する例を次に示します。
import LiteRTLM
// 1. Initialize the Engine with your model
let config = try EngineConfig(
modelPath: "path/to/model.litertlm",
backend: .gpu, // Use .cpu() for CPU execution
cacheDir: NSTemporaryDirectory()
)
let engine = Engine(engineConfig: config)
try await engine.initialize()
// 2. Start a new Conversation
let conversation = try await engine.createConversation()
// 3. Send a message and print the response
let response = try await conversation.sendMessage(Message("What is the capital of France?"))
print(response.toString)
スタートガイド
このセクションでは、LiteRT-LM Swift API をアプリに統合する手順について説明します。
Swift Package Manager(SPM)
Swift Package Manager を使用して、LiteRT-LM を Xcode プロジェクトに統合できます。
- Xcode でプロジェクトを開き、[File] > [Add Package Dependencies...] の順に移動します。
- パッケージ リポジトリの URL を入力します。
https://github.com/google-ai-edge/LiteRT-LM - LiteRTLM ライブラリを選択して、アプリケーション ターゲットに追加します。
Package.swift を使用してパッケージを開発している場合は、依存関係に追加します。
dependencies: [
.package(url: "https://github.com/google-ai-edge/LiteRT-LM", from: "0.12.0")
]
Core API ガイド
このセクションでは、LiteRT-LM Swift API を使用するための基本的なコンポーネントとワークフローについて詳しく説明します。これには、エンジンの初期化、会話の管理、メッセージの送信が含まれます。
Engine を初期化する
Engine は、モデルの読み込み、リソース割り当て、ライフサイクル管理を処理します。
import LiteRTLM
let engineConfig = try EngineConfig(
modelPath: "path/to/your/model.litertlm",
backend: .gpu, // Use .gpu for Metal hardware acceleration
maxNumTokens: 512, // Size of the KV-cache
cacheDir: NSTemporaryDirectory() // Writable directory for compilation cache
)
let engine = Engine(engineConfig: engineConfig)
try await engine.initialize()
会話を作成する
Conversation は、チャット履歴、システム指示、サンプラー構成を管理します。
// Configure custom sampling parameters
let samplerConfig = try SamplerConfig(
topK: 40,
topP: 0.95,
temperature: 0.7
)
// Create the conversation config with system instructions
let config = ConversationConfig(
systemMessage: Message("You are a helpful assistant."),
samplerConfig: samplerConfig
)
let conversation = try await engine.createConversation(with: config)
メッセージの送信
モデルとのやり取りは、同期または非同期(ストリーミング)で行うことができます。
同期の例
let response = try await conversation.sendMessage(Message("Hello!"))
print(response.toString)
非同期(ストリーミング)の例
let message = Message("Tell me a long story.")
for try await chunk in conversation.sendMessageStream(message) {
// Output response chunks in real-time
print(chunk.toString, terminator: "")
}
print()
マルチモダリティ
ビジョン機能または音声機能を使用するには、エンジン初期化時に専用のバックエンドを構成する必要があります。
let engineConfig = try EngineConfig(
modelPath: "path/to/multimodal_model.litertlm",
backend: .gpu,
visionBackend: .cpu(), // Enable CPU vision executor
audioBackend: .cpu(), // Enable CPU audio executor
cacheDir: NSTemporaryDirectory()
)
let engine = Engine(engineConfig: engineConfig)
try await engine.initialize()
画像入力(Vision)
パスまたは RAW バイトとして画像を指定します。
let imagePath = Bundle.main.path(forResource: "scenery", ofType: "jpg")!
let message = Message(contents: [
Content.imageFile(imagePath),
Content.text("Describe this image.")
])
let response = try await conversation.sendMessage(message)
print(response.toString)
音声入力
音声パスを指定します。
let audioPath = Bundle.main.path(forResource: "recording", ofType: "wav")!
let message = Message(contents: [
Content.audioFile(audioPath),
Content.text("Transcribe this recording.")
])
let response = try await conversation.sendMessage(message)
print(response.toString)
🔴 新機能: マルチトークン予測(MTP)
マルチトークン予測(MTP)は、デコード速度を大幅に向上させるパフォーマンス最適化です。GPU/Metal バックエンドを使用するすべてのタスクで推奨されます。
MTP を使用するには、エンジンを初期化する前に試験運用版フラグで投機的デコードを有効にします。
import LiteRTLM
// Opt into experimental APIs to configure MTP
ExperimentalFlags.optIntoExperimentalAPIs()
ExperimentalFlags.enableSpeculativeDecoding = true
let engineConfig = try EngineConfig(
modelPath: "path/to/model.litertlm",
backend: .gpu,
cacheDir: NSTemporaryDirectory()
)
let engine = Engine(engineConfig: engineConfig)
try await engine.initialize()
ツールを定義して使用する
モデルがロジックを実行するために自動的に呼び出すことができるツールとして、Swift 構造体を定義できます。
Toolプロトコルに準拠します。@ToolParamプロパティ ラッパーを使用してパラメータを宣言します。run()メソッドを実装します。
import LiteRTLM
// 1. Define your custom tool
struct GetCurrentWeatherTool: Tool {
static let name = "get_current_weather"
static let description = "Get the current weather for a location."
@ToolParam(description: "The city and state, e.g. San Francisco, CA")
var location: String
@ToolParam(description: "The temperature unit to use (celsius or fahrenheit)")
var unit: String = "celsius"
func run() async throws -> Any {
// Call your weather API here
return [
"location": location,
"temperature": "22",
"unit": unit,
"condition": "sunny"
]
}
}
// 2. Register the tool in your conversation configuration
let config = ConversationConfig(
tools: [GetCurrentWeatherTool()]
)
let conversation = try await engine.createConversation(with: config)
// 3. The model will invoke the tool automatically if needed
let response = try await conversation.sendMessage(Message("What is the weather in Paris right now?"))
print(response.toString)