LiteRT-LM Swift API

تتيح لك واجهة برمجة التطبيقات Swift الخاصة بـ LiteRT-LM دمج النماذج اللغوية الكبيرة بشكل أصلي في تطبيقات iOS وmacOS. تتوفّر بالكامل ميزات مثل الوسائط المتعددة واستخدام الأدوات وتسريع وحدة معالجة الرسومات (من خلال Metal).

مقدمة

في ما يلي مثال على استخدام واجهة برمجة تطبيقات Swift لإعداد نموذج وإرسال رسالة:

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 في تطبيقك.

‫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: [
  .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. يمكنك تعريف المَعلمات باستخدام أداة تضمين السمة @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)