LiteRT-LM Swift API

Interfejs Swift API LiteRT-LM umożliwia natywną integrację dużych modeli językowych z aplikacjami na iOS i macOS. Funkcje takie jak wielomodowość, korzystanie z narzędziakceleracja GPU (za pomocą Metal) są w pełni obsługiwane.

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

Ta sekcja zawiera instrukcje dotyczące integrowania interfejsu LiteRT-LM Swift API z aplikacją.

Swift Package Manager (SPM)

Możesz zintegrować LiteRT-LM z projektem Xcode za pomocą menedżera pakietów Swift.

  1. Otwórz projekt w Xcode i kliknij File > Add Package Dependencies... (Plik > Dodaj zależności pakietu...).
  2. Wpisz adres URL repozytorium pakietów: https://github.com/google-ai-edge/LiteRT-LM
  3. 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 interfejsie Core API

W tej sekcji opisujemy podstawowe komponenty i procesy związane z korzystaniem z interfejsu LiteRT-LM Swift API, w tym inicjowanie silnika, zarządzanie rozmowami i wysyłanie wiadomości.

Inicjowanie silnika

Engine obsługuje ładowanie modelu, przydzielanie 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 interakcje z modelem synchronicznie lub asynchronicznie (przesyłanie strumieniowe).

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()

Wiele rodzajów

Aby korzystać z funkcji związanych z widzeniem lub dźwiękiem, podczas inicjowania silnika skonfiguruj specjalistyczne interfejsy backendu.

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 (Vision)

Prześlij 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ę audio:

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ść: prognozowanie wielu tokenów (MTP)

Prognozowanie 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 i używanie narzędzi

Możesz zdefiniować struktury Swift jako narzędzia, które model może automatycznie wywoływać w celu wykonania logiki.

  1. Zgodność z protokołem Tool.
  2. Zadeklaruj parametry za pomocą otoczki właściwości @ToolParam.
  3. Zaimplementuj metodę 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)