Linux 및 macOS 용 LiteRT-LM의 Python API입니다 (Windows 지원은 예정). 멀티모달리티 및 도구 사용 과 같은 기능이 지원되며 GPU 가속 은 예정되어 있습니다.
소개
다음은 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-nightly
# Using uv
uv pip install litert-lm-api-nightly
1. 엔진 초기화
Engine은 API의 진입점입니다. 모델 로드 및 리소스 관리를 처리합니다. 컨텍스트 관리자 (with 문 사용)로 사용하면 네이티브 리소스가 즉시 해제됩니다.
참고: 엔진을 초기화하는 데 모델을 로드하는 데 몇 초가 걸릴 수 있습니다.
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. 대화 만들기
Conversation은 모델과의 상호작용 상태와 기록을 관리합니다.
# 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. 메시지 전송
동기식 또는 비동기식 (스트리밍)으로 메시지를 보낼 수 있습니다.
동기식 예:
# 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": "..."})
비동기식 (스트리밍) 예:
# 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. 멀티모달리티
# 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. 도구 정의 및 사용
모델에서 자동으로 호출할 수 있는 도구로 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 및 유형 힌트를 사용하여 모델의 도구 스키마를 생성합니다.