LiteRT-LM Python API

API Python của LiteRT-LM cho Linux và macOS (sẽ sớm hỗ trợ Windows). Các tính năng như đa phương thứcsử dụng công cụ được hỗ trợ, trong khi tăng tốc GPU sắp ra mắt.

Giới thiệu

Dưới đây là một ứng dụng trò chuyện mẫu trên thiết bị đầu cuối được xây dựng bằng Python API:

import litert_lm

litert_lm.set_min_log_severity(litert_lm.LogSeverity.ERROR) # Hide log for TUI app

with litert_lm.Engine("path/to/model.litertlm") as engine:
  with engine.create_conversation() as conversation:
    while True:
      user_input = input("\n>>> ")
      for chunk in conversation.send_message_async(user_input):
        print(chunk["content"][0]["text"], end="", flush=True)

Bắt đầu

LiteRT-LM có sẵn dưới dạng một thư viện Python. Bạn có thể cài đặt phiên bản hằng ngày từ PyPI:

# Using pip
pip install litert-lm-api-nightly

# Using uv
uv pip install litert-lm-api-nightly

1. Khởi động Công cụ

Engine là điểm truy cập vào API. Lớp này xử lý việc tải mô hình và quản lý tài nguyên. Việc sử dụng lớp này làm trình quản lý bối cảnh (với câu lệnh with) đảm bảo rằng các tài nguyên gốc được phát hành ngay lập tức.

Lưu ý: Quá trình khởi động công cụ có thể mất vài giây để tải mô hình.

import litert_lm

# Initialize with the model path and optionally specify the backend.
# backend can be Backend.CPU (default). GPU support is upcoming.
with litert_lm.Engine(
    "path/to/your/model.litertlm",
    backend=litert_lm.Backend.CPU,
    # Optional: Pick a writable dir for caching compiled artifacts.
    # cache_dir="/tmp/litert-lm-cache"
) as engine:
    # ... Use the engine to create a conversation ...
    pass

2. Tạo cuộc trò chuyện

Conversation quản lý trạng thái và nhật ký tương tác của bạn với mô hình.

# Optional: Configure system instruction and initial messages
messages = [
    {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]},
]

# Create the conversation
with engine.create_conversation(messages=messages) as conversation:
    # ... Interact with the conversation ...
    pass

3. Gửi tin nhắn

Bạn có thể gửi thông báo đồng bộ hoặc không đồng bộ (truyền phát trực tiếp).

Ví dụ đồng bộ:

# Simple string input
response = conversation.send_message("What is the capital of France?")
print(response["content"][0]["text"])

# Or with full message structure
# response = conversation.send_message({"role": "user", "content": "..."})

Ví dụ về phương thức không đồng bộ (truyền phát trực tuyến):

# sendMessageAsync returns an iterator of response chunks
stream = conversation.send_message_async("Tell me a long story.")
for chunk in stream:
    # Chunks are dictionaries containing pieces of the response
    for item in chunk.get("content", []):
      if item.get("type") == "text":
        print(item["text"], end="", flush=True)
print()

4. Đa phương thức

# Initialize with vision and/or audio backends if needed
with litert_lm.Engine(
    "path/to/multimodal_model.litertlm",
    audio_backend=litert_lm.Backend.CPU,
    # vision_backend=litert_lm.Backend.CPU, (GPU support is upcoming)
) as engine:
    with engine.create_conversation() as conversation:
        user_message = {
            "role": "user",
            "content": [
                {"type": "audio", "path": "/path/to/audio.wav"},
                {"type": "text", "text": "Describe this audio."},
            ],
        }
        response = conversation.send_message(user_message)
        print(response["content"][0]["text"])

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

Bạn có thể xác định các hàm Python làm công cụ mà mô hình có thể tự động gọi.

def add_numbers(a: float, b: float) -> float:
    """Adds two numbers.

    Args:
        a: The first number.
        b: The second number.
    """
    return a + b

# Register the tool in the conversation
tools = [add_numbers]
with engine.create_conversation(tools=tools) as conversation:
    # The model will call add_numbers automatically if it needs to sum values
    response = conversation.send_message("What is 123 + 456?")
    print(response["content"][0]["text"])

LiteRT-LM sử dụng chuỗi tài liệu và gợi ý về kiểu của hàm để tạo giản đồ công cụ cho mô hình.