LiteRT-LM Swift API

Swift API ของ LiteRT-LM ช่วยให้คุณผสานรวมโมเดลภาษาขนาดใหญ่เข้ากับแอปพลิเคชัน iOS และ macOS ได้โดยตรง โดยรองรับฟีเจอร์ต่างๆ อย่างเต็มรูปแบบ เช่น มัลติโมดัล การใช้เครื่องมือ และการเร่งความเร็วด้วย GPU (ผ่าน Metal)

บทนำ

ตัวอย่างการใช้ Swift API เพื่อเริ่มต้นโมเดลและส่งข้อความมีดังนี้

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)

เริ่มต้นใช้งาน

ส่วนนี้มีวิธีการผสานรวม LiteRT-LM Swift API เข้ากับแอปพลิเคชัน

Swift Package Manager (SPM)

คุณสามารถผสานรวม LiteRT-LM เข้ากับโปรเจ็กต์ Xcode ได้โดยใช้ Swift Package Manager

  1. เปิดโปรเจ็กต์ใน Xcode แล้วไปที่ File > Add Package Dependencies...
  2. ป้อน URL ที่เก็บแพ็กเกจ https://github.com/google-ai-edge/LiteRT-LM
  3. เลือกไลบรารี LiteRTLM เพื่อเพิ่มลงในเป้าหมายของแอปพลิเคชัน

หากคุณกำลังพัฒนาแพ็กเกจโดยใช้ Package.swift ให้เพิ่มแพ็กเกจลงใน Dependencies ดังนี้

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

คู่มือ Core API

ส่วนนี้จะอธิบายรายละเอียดเกี่ยวกับคอมโพเนนต์และเวิร์กโฟลว์พื้นฐานสำหรับการใช้ LiteRT-LM Swift API ซึ่งรวมถึงการเริ่มต้นเครื่องมือ การจัดการการสนทนา และการส่งข้อความ

เริ่มต้นเครื่องมือ

Engine จะจัดการการโหลดโมเดล การจัดสรรทรัพยากร และการจัดการวงจรการทำงาน

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

สร้างการสนทนา

Conversation จะจัดการประวัติการแชท คำแนะนำของระบบ และการกำหนดค่าตัวอย่าง

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

ส่งข้อความ

คุณสามารถโต้ตอบกับโมเดลแบบซิงโครนัสหรืออะซิงโครนัส (สตรีมมิง)

ตัวอย่างแบบซิงโครนัส

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

ตัวอย่างแบบอะซิงโครนัส (สตรีมมิง)

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

มัลติโมดัล

หากต้องการใช้ฟีเจอร์ด้านวิชันซิสเต็มหรือเสียง ให้กำหนดค่าแบ็กเอนด์เฉพาะระหว่างการเริ่มต้นเครื่องมือ

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

อินพุตรูปภาพ (วิชันซิสเต็ม)

ระบุรูปภาพเป็นเส้นทางหรือไบต์ดิบ

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)

อินพุตเสียง

ระบุเส้นทางเสียง

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)

🔴 ใหม่: การคาดการณ์หลายโทเค็น (MTP)

การคาดการณ์หลายโทเค็น (MTP) เป็นการเพิ่มประสิทธิภาพที่ช่วยเร่งความเร็วในการถอดรหัสได้อย่างมาก โดยขอแนะนำให้ใช้กับงานทั้งหมดที่ใช้แบ็กเอนด์ GPU/Metal

หากต้องการใช้ MTP ให้เปิดใช้การถอดรหัสแบบคาดการณ์ในแฟล็กทดลองก่อนเริ่มต้นเครื่องมือ

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

กำหนดและใช้เครื่องมือ

คุณสามารถกำหนดโครงสร้าง Swift เป็นเครื่องมือที่โมเดลเรียกใช้โดยอัตโนมัติเพื่อดำเนินการตรรกะได้

  1. เป็นไปตามโปรโตคอล Tool
  2. ประกาศพารามิเตอร์โดยใช้ Wrapper พร็อพเพอร์ตี้ @ToolParam
  3. ใช้เมธอด 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)