Skip to content

fix(chat): make get_tokens() robust to non-alternating turn histories - #445

Merged
cpsievert merged 2 commits into
mainfrom
fix/get-tokens-unpaired-turns
Oct 12, 2026
Merged

cpsievert merged 2 commits into
mainfrom
fix/get-tokens-unpaired-turns

Conversation

@cpsievert

Copy link
Copy Markdown
Collaborator

Ports tidyverse/ellmer#1157 (fixes tidyverse/ellmer#1131).

Problem

Chat.get_tokens() computed per-turn token counts by pairing user and assistant turns positionally, which only works when turns strictly alternate. It raised ValueError for histories that don't:

  • a trailing user turn with no completed assistant response yet — this arises in normal use when a request fails after the user turn was recorded, or after add_turn()
  • consecutive assistant turns (possible via set_turns())
  • a lone user turn

Fix

The computation is now driven off complete assistant turns instead of turn positions. Each assistant turn's input token count is cumulative over everything sent so far, so the implied user tokens for a round trip is simply the difference between consecutive requests — no alternation assumption needed. Histories with no complete assistant turns now return an empty list, and output for well-formed histories (including tool-calling loops, where tool results ride in user turns) is unchanged.

The only remaining ValueError is for assistant turns that genuinely lack token counts (e.g. fabricated via set_turns()), pointing at .get_turns() for raw values as before.

Tests

New credential-free tests cover: trailing user turn, lone user turn, consecutive assistant turns, tool loops, and the missing-token-count error. Existing test_tokens_method expectations are unchanged.

get_tokens() computed per-turn token counts by pairing user and
assistant turns positionally, which only works when turns strictly
alternate. A trailing user turn with no completed assistant response
(e.g. after a failed request or add_turn()), consecutive assistant
turns, or a lone user turn raised ValueError.

The computation is now driven off complete assistant turns: since each
assistant turn's input token count is cumulative, implied user tokens
fall out of consecutive differences without any alternation assumption.
A history with no complete assistant turns now returns an empty list.

Ports tidyverse/ellmer#1157 (fixes tidyverse/ellmer#1131).
@cpsievert
cpsievert merged commit abdf399 into main Oct 12, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

get_tokens() fails with an unpaired user turn or partial assistant

1 participant