A API Swift do LiteRT-LM permite integrar modelos de linguagem grandes de forma nativa em aplicativos iOS e macOS. Recursos como multimodalidade, uso de ferramentas e aceleração de GPU (via Metal) são totalmente compatíveis.
Introdução
Confira um exemplo de como usar a API Swift para inicializar um modelo e enviar uma mensagem:
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)
Primeiros passos
Esta seção fornece instruções sobre como integrar a API LiteRT-LM Swift ao seu aplicativo.
Gerenciador de pacotes do Swift (SPM)
É possível integrar o LiteRT-LM ao seu projeto do Xcode usando o Gerenciador de pacotes do Swift.
- Abra seu projeto no Xcode e navegue até Arquivo > Adicionar dependências do pacote...
- Insira o URL do repositório de pacotes:
https://github.com/google-ai-edge/LiteRT-LM - Selecione a biblioteca LiteRTLM para adicioná-la ao destino do aplicativo.
Se você estiver desenvolvendo um pacote usando Package.swift, adicione-o às suas
dependências:
dependencies: [
.package(url: "https://github.com/google-ai-edge/LiteRT-LM", from: "0.12.0")
]
Guia da API principal
Esta seção detalha os componentes e fluxos de trabalho fundamentais para usar a API LiteRT-LM Swift, incluindo inicialização do mecanismo, gerenciamento de conversas e envio de mensagens.
Inicializar o mecanismo
O Engine gerencia o carregamento de modelos, a alocação de recursos e o gerenciamento do ciclo de vida.
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()
Criar uma conversa
Um Conversation gerencia o histórico de chat, as instruções do sistema e as configurações do sampler.
// 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)
Enviar mensagens
É possível interagir com o modelo de forma síncrona ou assíncrona (streaming).
Exemplo síncrono
let response = try await conversation.sendMessage(Message("Hello!"))
print(response.toString)
Exemplo assíncrono (streaming)
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()
Multimodalidade
Para usar recursos de visão ou áudio, configure os back-ends especializados durante a inicialização do mecanismo.
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()
Entrada de imagem (Visão)
Forneça uma imagem como um caminho ou bytes brutos:
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)
Entrada de áudio
Forneça um caminho de áudio:
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)
🔴 Novo: previsão de vários tokens (MTP)
A previsão de vários tokens (MTP, na sigla em inglês) é uma otimização de desempenho que acelera significativamente as velocidades de decodificação. É recomendável para todas as tarefas que usam back-ends de GPU/Metal.
Para usar o MTP, ative a decodificação especulativa nas flags experimentais antes de inicializar o mecanismo.
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()
Definir e usar ferramentas
É possível definir estruturas Swift como ferramentas que o modelo pode chamar automaticamente para executar a lógica.
- Obedeça ao protocolo
Tool. - Declare parâmetros usando o wrapper de propriedade
@ToolParam. - Implemente o método
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)