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를 사용하여 Xcode 프로젝트에 LiteRT-LM을 통합할 수 있습니다.
- 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는 모델 로드, 리소스 할당, 수명 주기 관리를 처리합니다.
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)
이미지를 경로 또는 원시 바이트로 제공합니다.
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)