agents icon indicating copy to clipboard operation
agents copied to clipboard

fix(llm): reposition mid-conversation instructions for Gemini gateway and Mistral

Open L65FREAD opened this issue 4 months ago • 1 comments

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 instructions request 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._run at serialization time — so stream.chat_ctx and the llm_request telemetry span keep the original roles, matching the plugins — gated by a model-prefix allowlist (currently google/). 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.

L65FREAD avatar Jul 28 '26 20:07 L65FREAD

CLA assistant check
All committers have signed the CLA.

CLAassistant avatar Jul 28 '26 20:07 CLAassistant