A API Python do LiteRT-LM para Linux, macOS e Windows. Recursos como multimodalidade, uso de ferramentas e aceleração de GPU e NPU são compatíveis.
Introdução
Confira um exemplo de app de chat de terminal criado com a API Python:
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)

Primeiros passos
O LiteRT-LM está disponível como uma biblioteca Python. É possível instalar o pacote do PyPI:
# Using pip
pip install litert-lm-api
# Using uv
uv pip install litert-lm-api
Inicializar o mecanismo
O Engine é o ponto de entrada da API. Ele processa o carregamento do modelo e o gerenciamento de recursos. Usá-lo como um gerenciador de contexto (com a instrução with) garante que os recursos sejam liberados imediatamente.
Observação:a inicialização do mecanismo pode levar vários segundos para carregar o modelo.
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
Criar uma conversa
Uma Conversation gerencia o estado e o histórico da sua interação com o modelo.
# 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
Enviar mensagens
É possível enviar mensagens de maneira síncrona ou assíncrona (streaming).
Os métodos send_message e send_message_async aceitam:
- Uma
str(encapsulada automaticamente como uma mensagem do usuário). - Um objeto
litert_lm.Contents(para entradas multimodais). - Um objeto
litert_lm.Message(para estrutura de mensagem completa). - Um objeto de dicionário semelhante a JSON como entrada de modelo de prompt.
Exemplo síncrono :
# 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?"))
Exemplo assíncrono (streaming) :
# 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()
🔴 Novo: previsão de vários tokens (MTP)
A previsão de vários tokens (MTP, na sigla em inglês) é uma otimização de desempenho que acelera significativamente as velocidades de decodificação. A MTP é recomendada universalmente para todas as tarefas em back-ends de GPU.
Para usar a MTP, ative a decodificação especulativa ao inicializar o mecanismo.
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"])
Multimodalidade
# 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"])
Definir e usar ferramentas
É possível definir funções Python como ferramentas que o modelo pode chamar automaticamente.
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"])
O LiteRT-LM usa a docstring e as dicas de tipo da função para gerar o esquema de ferramentas do modelo.