Local LLMs
4.25.5kata 5 de 5

Streaming y buffering

Streaming de tokens con buffer para latencia baja

llama.cpp soporta streaming de respuestas token-a-token, lo que reduce el tiempo percibido por el usuario desde 'completa la respuesta' hasta 'recibe el primer token'. Para aplicaciones interactivas (chatbots, asistentes), el streaming es crítico.

El streaming con llama-server se obtiene automáticamente a través de la API compatible con OpenAI — simplemente establecer `stream=True` en la solicitud hace que la respuesta llegue como un flujo de eventos SSE (Server-Sent Events). Esto permite al cliente mostrar la respuesta conforme se genera, en lugar de esperar a que termine completamente.

El buffering estratégico mejora la experiencia: en lugar de renderizar cada token individualmente (que causa parpadeo visible), acumular 2-3 tokens antes de actualizar la UI proporciona un flujo más natural. El balance es: esperar muy poco (parpadeo), esperar mucho (latencia percibida alta).

structure.txt
# llama.cpp streaming with OpenAI-compatible API
from openai import OpenAI

client = OpenAI(
    base_url='http://localhost:8080/v1',
    api_key='na',
)

# Streaming response: tokens arrive one at a time
response = client.chat.completions.create(
    model='local',
    messages=[{'role': 'user', 'content': 'Explain quantum computing in 2 sentences.'}],
    stream=True,  # enable token-by-token streaming
    max_tokens=256,
    temperature=0.0,
)

# Buffering strategy: accumulate 2-3 tokens before rendering
buffer = []
buffer_size = 2

for event in response:
    if event.choices[0].delta.content:
        token = event.choices[0].delta.content
        buffer.append(token)

        if len(buffer) >= buffer_size:
            text = ''.join(buffer)
            print(text, end='', flush=True)  # render buffered tokens
            buffer = []

# Flush remaining tokens
if buffer:
    print(''.join(buffer), end='', flush=True)

Debugging lab

Detecta y corrige el error en el código.

0/1 tests passing0%
  1. 01

    # No streaming: wait for full response before rendering response = client.chat.completions.create( model='local', messages=[{'role': 'user', 'content': 'Tell me a story.'}], stream=False, # synchronous, full response max_tokens=512, ) print(response.choices[0].message.content) # renders only when complete