LiteRT-LM Python API

Linux, macOS, Windows용 LiteRT-LM의 Python API 멀티모달리티, 도구 사용, GPU 및 NPU 가속과 같은 기능이 지원됩니다.

소개

다음은 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)

시작하기

LiteRT-LM은 Python 라이브러리로 제공됩니다. PyPI에서 패키지를 설치할 수 있습니다.

# Using pip
pip install litert-lm-api

# Using uv
uv pip install litert-lm-api

엔진 초기화

Engine은 API의 진입점입니다. 모델 로딩과 리소스 관리를 처리합니다. with 문과 함께 컨텍스트 관리자로 사용하면 리소스가 즉시 해제됩니다.

참고: 엔진을 초기화하면 모델을 로드하는 데 몇 초가 걸릴 수 있습니다.

import litert_lm

# Initialize with the model path and optionally specify the backend.
# backend can be Backend.CPU() (default), Backend.GPU() or Backend.NPU().
with litert_lm.Engine(
    "path/to/your/model.litertlm",
    backend=litert_lm.Backend.GPU(),
    # 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

대화 만들기

Conversation는 모델과의 상호작용 상태와 기록을 관리합니다.

# Optional: Configure system instruction and initial messages
messages = [litert_lm.Message.system("You are a helpful assistant.")]

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

메시지 보내기

동기 또는 비동기 (스트리밍)로 메시지를 보낼 수 있습니다.

send_messagesend_message_async 메서드는 다음을 허용합니다.

  • str (사용자 메시지로 자동 래핑됨)
  • litert_lm.Contents 객체 (멀티모달 입력의 경우)
  • litert_lm.Message 객체 (전체 메시지 구조용)
  • 프롬프트 템플릿 입력으로 json과 유사한 사전 객체입니다.

동기 예:

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

# Or with a Message object
# response = conversation.send_message(litert_lm.Message.user("What is the capital of France?"))

비동기 (스트리밍) 예:

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

🔴 신규: 멀티 토큰 예측 (MTP)

다중 토큰 예측 (MTP)은 디코딩 속도를 크게 가속화하는 성능 최적화입니다. MTP는 GPU 백엔드의 모든 작업에 권장됩니다.

MTP를 사용하려면 엔진을 초기화할 때 추측 디코딩을 사용 설정하세요.

import litert_lm

# Enable MTP by setting enable_speculative_decoding=True
with litert_lm.Engine(
    "path/to/your/model.litertlm",
    backend=litert_lm.Backend.GPU(),
    enable_speculative_decoding=True,
) as engine:
    with engine.create_conversation() as conversation:
        response = conversation.send_message("What is the capital of France?")
        print(response["content"][0]["text"])

멀티모달리티

# 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.GPU(),
) as engine:
    with engine.create_conversation() as conversation:
        response = conversation.send_message(
            litert_lm.Contents.of(
                "Describe this audio.",
                litert_lm.Content.AudioFile(absolute_path="/path/to/audio.wav"),
            )
        )
        print(response["content"][0]["text"])

도구 정의 및 사용

모델이 자동으로 호출할 수 있는 도구로 Python 함수를 정의할 수 있습니다.

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은 함수의 docstring과 유형 힌트를 사용하여 모델의 도구 스키마를 생성합니다.