mirror of
https://github.com/livekit/agents.git
synced 2026-12-06 04:08:35 +00:00
212 lines
8.3 KiB
Python
212 lines
8.3 KiB
Python
"""Baseten LLM: per-model handling of mid-conversation system messages.
|
|
|
|
LiveKit appends ``generate_reply(instructions=...)`` (and the expressive TTS guide) to
|
|
the chat context as a trailing system message. Some chat templates only accept a leading
|
|
system message, so for an explicit list of model ids the plugin inlines later system
|
|
messages as ``<instructions>``-wrapped user messages. Every other model id, including
|
|
other Gemma and Qwen ids, must keep receiving the request untouched unless the caller
|
|
opts in.
|
|
|
|
These tests capture the JSON body the plugin POSTs to a local endpoint, so they exercise the
|
|
real serializer path without network access.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any, cast
|
|
|
|
import pytest
|
|
|
|
from livekit.agents.llm import ChatContext, FunctionCall, FunctionCallOutput
|
|
from livekit.agents.types import NOT_GIVEN, NotGivenOr
|
|
from livekit.plugins.baseten import LLM
|
|
|
|
from .utils.chat_completions import serve
|
|
|
|
pytestmark = pytest.mark.unit
|
|
|
|
PREAMBLE = "You are a helpful assistant."
|
|
INSTRUCTIONS = "Ask the caller for the year they were born."
|
|
INLINED = f"<instructions>\n{INSTRUCTIONS}\n</instructions>"
|
|
|
|
INLINE_MODELS = ["Qwen/Qwen3.8-27B"]
|
|
PASSTHROUGH_MODELS = [
|
|
"openai/gpt-oss-120b",
|
|
"zai-org/GLM-5.2",
|
|
"meta-llama/Llama-4-Maverick-17B-128E-Instruct",
|
|
"deepseek-ai/DeepSeek-V3-0324",
|
|
"moonshotai/Kimi-K2-Instruct",
|
|
"google/gemma-4-31B-it",
|
|
# same family as the opted-in id, but not on the list
|
|
"Qwen/Qwen3.5-35B-A3B-FP8",
|
|
]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
_ONE_TOKEN = (
|
|
b'data: {"id":"chatcmpl-1","object":"chat.completion.chunk","created":0,"model":"test",'
|
|
b'"choices":[{"index":0,"delta":{"role":"assistant","content":"ok"},"finish_reason":null}]}'
|
|
b"\n\ndata: [DONE]\n\n"
|
|
)
|
|
|
|
|
|
async def _sent_messages(
|
|
model: str, chat_ctx: ChatContext, *, inline: NotGivenOr[bool] = NOT_GIVEN
|
|
) -> list[dict[str, Any]]:
|
|
"""The messages a Baseten LLM sends for `chat_ctx`, recorded by a local endpoint."""
|
|
async with serve(_ONE_TOKEN) as (base_url, received):
|
|
llm_model = LLM(
|
|
model=model,
|
|
api_key="test",
|
|
base_url=base_url,
|
|
inline_mid_conversation_instructions=inline,
|
|
)
|
|
try:
|
|
async with llm_model.chat(chat_ctx=chat_ctx) as stream:
|
|
async for _ in stream:
|
|
pass
|
|
finally:
|
|
await llm_model.aclose()
|
|
|
|
assert len(received) == 1
|
|
return cast(list[dict[str, Any]], json.loads(received[0].body)["messages"])
|
|
|
|
|
|
def _per_turn_ctx() -> ChatContext:
|
|
# the shape generate_reply(instructions=...) produces: a trailing system message
|
|
chat_ctx = ChatContext.empty()
|
|
chat_ctx.add_message(role="system", content=[PREAMBLE])
|
|
chat_ctx.add_message(role="assistant", content=["Hello! How can I help you?"])
|
|
chat_ctx.add_message(role="user", content=["I'd like to refill my prescription."])
|
|
chat_ctx.add_message(role="system", content=[INSTRUCTIONS])
|
|
return chat_ctx
|
|
|
|
|
|
def _tool_ctx() -> ChatContext:
|
|
chat_ctx = ChatContext.empty()
|
|
chat_ctx.add_message(role="system", content=[PREAMBLE])
|
|
chat_ctx.add_message(role="user", content=["What's the weather in SF?"])
|
|
chat_ctx.items.append(
|
|
FunctionCall(call_id="call_1", name="get_weather", arguments='{"city": "SF"}')
|
|
)
|
|
chat_ctx.items.append(
|
|
FunctionCallOutput(call_id="call_1", name="get_weather", output="sunny", is_error=False)
|
|
)
|
|
chat_ctx.add_message(role="system", content=[INSTRUCTIONS])
|
|
return chat_ctx
|
|
|
|
|
|
def _plain_ctx() -> ChatContext:
|
|
chat_ctx = ChatContext.empty()
|
|
chat_ctx.add_message(role="system", content=[PREAMBLE])
|
|
chat_ctx.add_message(role="user", content=["Hi!"])
|
|
chat_ctx.add_message(role="assistant", content=["Hello! How can I help you?"])
|
|
chat_ctx.add_message(role="user", content=["Tell me a joke."])
|
|
return chat_ctx
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Model-id detection: an explicit allow-list, not a family match
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# New behaviour: opted-in models get inlined instructions
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize("model", INLINE_MODELS)
|
|
async def test_per_turn_instructions_are_inlined_for_single_system_models(model: str) -> None:
|
|
messages = await _sent_messages(model, _per_turn_ctx())
|
|
|
|
assert [m["role"] for m in messages] == ["system", "assistant", "user", "user"]
|
|
assert messages[0] == {"role": "system", "content": PREAMBLE}
|
|
assert messages[-1] == {"role": "user", "content": INLINED}
|
|
|
|
|
|
async def test_inlining_preserves_tool_call_history() -> None:
|
|
messages = await _sent_messages("Qwen/Qwen3.8-27B", _tool_ctx())
|
|
|
|
assert [m["role"] for m in messages] == ["system", "user", "assistant", "tool", "user"]
|
|
assert messages[2]["tool_calls"][0]["id"] == "call_1"
|
|
assert messages[2]["tool_calls"][0]["function"]["name"] == "get_weather"
|
|
assert messages[3] == {"role": "tool", "tool_call_id": "call_1", "content": "sunny"}
|
|
assert messages[-1] == {"role": "user", "content": INLINED}
|
|
|
|
|
|
async def test_inlining_does_not_mutate_the_callers_chat_ctx() -> None:
|
|
chat_ctx = _per_turn_ctx()
|
|
snapshot = chat_ctx.to_dict()
|
|
|
|
await _sent_messages("Qwen/Qwen3.8-27B", chat_ctx)
|
|
|
|
assert chat_ctx.to_dict() == snapshot
|
|
last = chat_ctx.items[-1]
|
|
assert last.type == "message" and last.role == "system"
|
|
|
|
|
|
async def test_empty_mid_conversation_system_message_is_dropped_when_inlining() -> None:
|
|
chat_ctx = ChatContext.empty()
|
|
chat_ctx.add_message(role="system", content=[PREAMBLE])
|
|
chat_ctx.add_message(role="user", content=["Hi!"])
|
|
chat_ctx.add_message(role="system", content=[""])
|
|
|
|
messages = await _sent_messages("Qwen/Qwen3.8-27B", chat_ctx)
|
|
|
|
assert [m["role"] for m in messages] == ["system", "user"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Regression: every other model id is untouched
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize("model", PASSTHROUGH_MODELS)
|
|
async def test_per_turn_instructions_pass_through_for_openai_style_models(model: str) -> None:
|
|
messages = await _sent_messages(model, _per_turn_ctx())
|
|
|
|
assert [m["role"] for m in messages] == ["system", "assistant", "user", "system"]
|
|
assert messages[0] == {"role": "system", "content": PREAMBLE}
|
|
assert messages[-1] == {"role": "system", "content": INSTRUCTIONS}
|
|
|
|
|
|
async def test_tool_history_passes_through_for_openai_style_models() -> None:
|
|
messages = await _sent_messages("openai/gpt-oss-120b", _tool_ctx())
|
|
|
|
assert [m["role"] for m in messages] == ["system", "user", "assistant", "tool", "system"]
|
|
assert messages[3] == {"role": "tool", "tool_call_id": "call_1", "content": "sunny"}
|
|
|
|
|
|
async def test_conversation_without_mid_system_messages_is_identical_across_models() -> None:
|
|
# when there is nothing to inline, both code paths must produce the same request
|
|
inlined = await _sent_messages("Qwen/Qwen3.8-27B", _plain_ctx())
|
|
passthrough = await _sent_messages("openai/gpt-oss-120b", _plain_ctx())
|
|
|
|
assert inlined == passthrough
|
|
assert [m["role"] for m in inlined] == ["system", "user", "assistant", "user"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Explicit override
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize("model", ["google/gemma-4-31B-it", "my-dedicated-model"])
|
|
async def test_override_enables_inlining_for_models_not_on_the_list(model: str) -> None:
|
|
messages = await _sent_messages(model, _per_turn_ctx(), inline=True)
|
|
|
|
assert [m["role"] for m in messages] == ["system", "assistant", "user", "user"]
|
|
assert messages[-1] == {"role": "user", "content": INLINED}
|
|
|
|
|
|
async def test_override_disables_inlining_for_a_listed_model() -> None:
|
|
messages = await _sent_messages("Qwen/Qwen3.8-27B", _per_turn_ctx(), inline=False)
|
|
|
|
assert [m["role"] for m in messages] == ["system", "assistant", "user", "system"]
|
|
assert messages[-1] == {"role": "system", "content": INSTRUCTIONS}
|