Interfejs Swift API LiteRT-LM umożliwia natywną integrację dużych modeli językowych z aplikacjami na iOS i macOS. W pełni obsługiwane są funkcje takie jak wielomodalność, korzystanie z narzędzi, i akceleracja GPU (za pomocą Metal).
Wprowadzenie
Oto przykład użycia interfejsu Swift API do zainicjowania modelu i wysłania wiadomości:
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)
Pierwsze kroki
W tej sekcji znajdziesz instrukcje, jak zintegrować interfejs Swift API LiteRT-LM z aplikacją.
Swift Package Manager (SPM)
Możesz zintegrować LiteRT-LM z projektem Xcode za pomocą Swift Package Manager.
- Otwórz projekt w Xcode i kliknij File > Add Package Dependencies... (Plik > Dodaj zależności pakietu).
- Wpisz adres URL repozytorium pakietu:
https://github.com/google-ai-edge/LiteRT-LM - Wybierz bibliotekę LiteRTLM , aby dodać ją do celu aplikacji.
Jeśli tworzysz pakiet za pomocą Package.swift, dodaj go do zależności:
dependencies: [
.package(url: "https://github.com/google-ai-edge/LiteRT-LM", from: "0.12.0")
]
Przewodnik po podstawowym interfejsie API
W tej sekcji opisujemy podstawowe komponenty i procesy związane z korzystaniem z interfejsu Swift API LiteRT-LM, w tym inicjowanie silnika, zarządzanie rozmowami i wysyłanie wiadomości.
Inicjowanie silnika
Engine obsługuje wczytywanie modelu, alokację zasobów i zarządzanie cyklem życia.
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()
Tworzenie rozmowy
Conversation zarządza historią czatu, instrukcjami systemowymi i konfiguracjami próbnika.
// 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)
Wysyłanie wiadomości
Możesz wchodzić w interakcję z modelem synchronicznie lub asynchronicznie (strumieniowo).
Przykład synchroniczny
let response = try await conversation.sendMessage(Message("Hello!"))
print(response.toString)
Przykład asynchroniczny (strumieniowy)
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()
Wielomodalność
Aby korzystać z funkcji związanych z obrazem lub dźwiękiem, podczas inicjowania silnika skonfiguruj specjalistyczne backendy.
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()
Obraz wejściowy (obraz)
Podaj obraz jako ścieżkę lub surowe bajty:
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)
Wejście audio
Podaj ścieżkę dźwięku:
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)
🔴 Nowość: przewidywanie wielu tokenów (MTP)
Przewidywanie wielu tokenów (MTP) to optymalizacja wydajności, która znacznie przyspiesza dekodowanie. Jest to zalecane w przypadku wszystkich zadań korzystających z backendów GPU/Metal.
Aby używać MTP, przed zainicjowaniem silnika włącz spekulatywne dekodowanie we flagach eksperymentalnych.
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()
Definiowanie narzędzi i korzystanie z nich
Możesz zdefiniować struktury Swift jako narzędzia, które model może automatycznie wywoływać w celu wykonania logiki.
- Zgodność z protokołem
Tool. - Deklarowanie parametrów za pomocą otoki właściwości
@ToolParam. - Implementowanie metody
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)