LiteRT-LM Swift API

API Swift của LiteRT-LM cho phép bạn tích hợp các mô hình ngôn ngữ lớn một cách tự nhiên vào các ứng dụng iOS và macOS. Các tính năng như đa phương thức, sử dụng công cụtăng tốc GPU (thông qua Metal) được hỗ trợ đầy đủ.

Giới thiệu

Sau đây là ví dụ về cách sử dụng API Swift để khởi tạo một mô hình và gửi một thông báo:

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)

Bắt đầu

Phần này cung cấp hướng dẫn về cách tích hợp LiteRT-LM Swift API vào ứng dụng của bạn.

Trình quản lý gói Swift (SPM)

Bạn có thể tích hợp LiteRT-LM vào dự án Xcode bằng Trình quản lý gói Swift.

  1. Mở dự án trong Xcode rồi chuyển đến File (Tệp) > Add Package Dependencies (Thêm các phần phụ thuộc của gói)...
  2. Nhập URL của kho lưu trữ gói: https://github.com/google-ai-edge/LiteRT-LM
  3. Chọn thư viện LiteRTLM để thêm thư viện này vào mục tiêu ứng dụng của bạn.

Nếu bạn đang phát triển một gói bằng Package.swift, hãy thêm gói đó vào các phần phụ thuộc của bạn:

dependencies: [
  .package(url: "https://github.com/google-ai-edge/LiteRT-LM", from: "0.12.0")
]

Hướng dẫn về Core API

Phần này trình bày chi tiết các thành phần và quy trình cơ bản để sử dụng LiteRT-LM Swift API, bao gồm cả việc khởi tạo công cụ, quản lý cuộc trò chuyện và gửi tin nhắn.

Khởi chạy Công cụ

Engine xử lý việc tải mô hình, phân bổ tài nguyên và quản lý vòng đời.

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

Tạo cuộc trò chuyện

Conversation quản lý nhật ký trò chuyện, hướng dẫn hệ thống và cấu hình trình lấy mẫu.

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

Gửi tin nhắn

Bạn có thể tương tác với mô hình này một cách đồng bộ hoặc không đồng bộ (truyền trực tuyến).

Ví dụ đồng bộ

let response = try await conversation.sendMessage(Message("Hello!"))
print(response.toString)

Ví dụ không đồng bộ (Phát trực tuyến)

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

Đa phương thức

Để sử dụng các tính năng về thị giác hoặc âm thanh, hãy nhớ định cấu hình các phần phụ trợ chuyên biệt trong quá trình khởi chạy công cụ.

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

Đầu vào hình ảnh (Thị giác)

Cung cấp hình ảnh dưới dạng đường dẫn hoặc byte thô:

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)

Đầu vào âm thanh

Cung cấp đường dẫn âm thanh:

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)

🔴 Mới: Dự đoán nhiều mã thông báo (MTP)

Dự đoán nhiều token (MTP) là một phương pháp tối ưu hoá hiệu suất giúp tăng tốc đáng kể tốc độ giải mã. Đây là lựa chọn được khuyến nghị cho mọi tác vụ sử dụng các chương trình phụ trợ GPU/Metal.

Để sử dụng MTP, hãy bật tính năng giải mã suy đoán trong các cờ thử nghiệm trước khi khởi động công cụ.

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

Xác định và sử dụng công cụ

Bạn có thể xác định các cấu trúc Swift làm công cụ mà mô hình có thể tự động gọi để thực thi logic.

  1. Tuân thủ giao thức Tool.
  2. Khai báo các tham số bằng trình bao bọc thuộc tính @ToolParam.
  3. Triển khai phương thức 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)