API-ja Swift e LiteRT-LM ju lejon të integroni modele të mëdha gjuhësore në mënyrë native në aplikacionet iOS dhe macOS . Funksione të tilla si multimodaliteti , përdorimi i mjeteve dhe përshpejtimi i GPU-së (nëpërmjet Metal) mbështeten plotësisht.
Hyrje
Ja një shembull i përdorimit të Swift API për të inicializuar një model dhe për të dërguar një mesazh:
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)
Fillimi
Ky seksion ofron udhëzime se si të integroni API-n LiteRT-LM Swift në aplikacionin tuaj.
Menaxheri i Paketave Swift (SPM)
Ju mund ta integroni LiteRT-LM në projektin tuaj Xcode duke përdorur Swift Package Manager.
- Hapni projektin tuaj në Xcode dhe shkoni te File > Add Package Dependencies...
- Futni URL-në e depove të paketës:
https://github.com/google-ai-edge/LiteRT-LM - Zgjidhni bibliotekën LiteRTLM për ta shtuar atë në objektivin e aplikacionit tuaj.
Nëse po zhvilloni një paketë duke përdorur Package.swift , shtojeni atë te varësitë tuaja:
dependencies: [
.package(url: "https://github.com/google-ai-edge/LiteRT-LM", from: "0.12.0")
]
Udhëzuesi i API-t bazë
Ky seksion detajon komponentët themelorë dhe rrjedhat e punës për përdorimin e LiteRT-LM Swift API, duke përfshirë inicializimin e motorit, menaxhimin e bisedave dhe dërgimin e mesazheve.
Inicializoni Motorin
Engine merret me ngarkimin e modelit, ndarjen e burimeve dhe menaxhimin e ciklit jetësor.
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()
Krijo një bisedë
Një Conversation menaxhon historikun e bisedave, udhëzimet e sistemit dhe konfigurimet e mostrave.
// 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)
Dërgo Mesazhe
Ju mund të bashkëveproni me modelin në mënyrë sinkrone ose asinkrone (transmetim).
Shembull Sinkron
let response = try await conversation.sendMessage(Message("Hello!"))
print(response.toString)
Shembull Asinkron (Transmetim)
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()
Multi-modalitet
Për të përdorur veçoritë e shikimit ose audios, sigurohuni që të konfiguroni backend-et e specializuara gjatë inicializimit të motorit.
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()
Hyrja e Imazhit (Vizioni)
Jepni një imazh si shteg ose bajt të papërpunuar:
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)
Hyrja audio
Jepni një shteg 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)
🔴 E re: Parashikimi me shumë shenja (MTP)
Parashikimi i Shumë-Tokenëve (MTP) është një optimizim i performancës që përshpejton ndjeshëm shpejtësitë e dekodimit. Rekomandohet universalisht për të gjitha detyrat që përdorin backend-e GPU/Metal.
Për të përdorur MTP-në, aktivizoni dekodimin spekulativ në flamujt eksperimentalë përpara se të inicializoni motorin.
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()
Përcaktoni dhe Përdorni Mjetet
Ju mund të përcaktoni strukturat Swift si mjete që modeli mund t'i thërrasë automatikisht për të ekzekutuar logjikën.
- Përputhet me protokollin
Tool. - Deklaroni parametrat duke përdorur mbështjellësin e vetive
@ToolParam. - Implementoni metodën
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)