agents
agents copied to clipboard
fix(llm): reposition mid-conversation instructions for Gemini gateway and Mistral
Summary
generate_reply(instructions=...) appends the per-turn instructions as a trailing system message. Two serialization paths mishandled it:
- LiveKit Inference / Gemini: the gateway serializes with the openai format, which passes system messages through as-is — and Gemini can't take a system role after the start of the conversation.
- Mistral: the Conversations serializer maps every system message onto the
instructionsrequest field, so the trailing per-turn message silently overwrote the agent's base prompt.
Both now route through the SDK's existing convert_mid_conversation_instructions (already used by the google/anthropic/aws serializers), which keeps the first system message as the base preamble and rewrites later ones as position-preserving <instructions>-wrapped user turns.
Where the conversion happens:
- The inference gateway applies it in
LLMStream._runat serialization time — sostream.chat_ctxand thellm_requesttelemetry span keep the original roles, matching the plugins — gated by a model-prefix allowlist (currentlygoogle/). OpenAI-compatible gateway providers keep the system role untouched. AIPlatformLLM(Vertex AI Model Garden), which reuses the shared stream with the openai wire format, opts in unconditionally since self-deployed model templates commonly reject non-leading system roles.- The mistralai serializer applies it directly, same as google/anthropic/aws.
Helper hardening while touching it:
- A system message only counts as the preamble when no conversation content precedes it — previously, with no base system message anywhere, a trailing per-turn message stayed a trailing system message.
- Text-less mid-conversation system messages are dropped instead of leaking through (they could shadow the base prompt on Mistral).
Testing
- New unit tests: gateway repositioning end-to-end (google model converts, openai model passes through, original ctx not mutated), mistral serializer conversion, the no-preamble edge, and the empty-system-message edge.
- Full unit suite: 1177 passed (the 9 errors are pre-existing on the base commit too); ruff and full-repo mypy clean.