Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(server): accept running usage in remote chat streams (#662)
Krisztian Gajdard8053bd4deb3
diff --git a/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py b/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.pyindex 0b694d625..22ca6316d 100644--- a/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py+++ b/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py@@ -218,9 +218,9 @@ class ChatStreamParser:payload = _json(data, max_bytes=_MAX_EVENT_BYTES)choices = self._parse_choices(payload.get("choices"), stream=True)clean = self._envelope(choices, stream=True)- if payload.get("usage") is not None:- if len(self._finished) != self.choices or self._usage is not None:- raise _invalid()+ # Upstreams may stream a running count on every chunk. Only the last+ # usage after every choice finishes is the request's usage.+ if payload.get("usage") is not None and len(self._finished) == self.choices:self._usage = _usage(payload["usage"])clean["usage"] = self._usagereturn cleandiff --git a/packages/sie_server/tests/adapters/test_remote_openai_chat.py b/packages/sie_server/tests/adapters/test_remote_openai_chat.pyindex 4b1147b4e..2a04cc3dd 100644--- a/packages/sie_server/tests/adapters/test_remote_openai_chat.py+++ b/packages/sie_server/tests/adapters/test_remote_openai_chat.py@@ -111,17 +111,50 @@ def test_buffered_chat_refuses_invalid_choices(choices: list[dict]) -> None:def test_multiple_choices_must_all_finish() -> None:parser = ChatStreamParser("model", choices=2)parser.parse(wire([choice(index=0, stream=True)]))+ early = parser.parse(wire([], usage=USAGE))+ assert early is not None+ assert "usage" not in earlywith pytest.raises(RemoteUpstreamError):- parser.parse(wire([], usage=USAGE))+ parser.parse(b"[DONE]")-def test_duplicate_finished_choice_and_duplicate_usage_fail() -> None:+def test_duplicate_finished_choice_fails() -> None:parser = ChatStreamParser("model")parser.parse(wire([choice(stream=True)], usage=USAGE))with pytest.raises(RemoteUpstreamError):parser.parse(wire([choice(stream=True)]))+++def test_running_usage_is_not_final_and_the_last_usage_after_every_finish_stands() -> None:+ parser = ChatStreamParser("model")+ running = {"prompt_tokens": 37, "completion_tokens": 1, "total_tokens": 38}+ final = {**USAGE, "prompt_tokens_details": {"cached_tokens": 3}}+ first = parser.parse(wire([choice(stream=True, finish=None, content="ans")], usage=running))+ finished = parser.parse(wire([choice(stream=True, content="wer")], usage=USAGE))+ trailing = parser.parse(wire([], usage=final))+ assert first is not None+ assert "usage" not in first+ assert finished is not None+ assert finished["usage"] == USAGE+ assert trailing is not None+ assert trailing["usage"] == final+ assert parser.parse(b"[DONE]") is None+ parser.finish()+++def test_running_usage_cannot_stand_in_for_the_final_usage() -> None:+ parser = ChatStreamParser("model")+ parser.parse(wire([choice(stream=True, finish=None)], usage=USAGE))+ parser.parse(wire([choice(stream=True)]))+ with pytest.raises(RemoteUpstreamError):+ parser.parse(b"[DONE]")+++def test_invalid_usage_after_every_finish_fails() -> None:+ parser = ChatStreamParser("model")+ parser.parse(wire([choice(stream=True)], usage=USAGE))with pytest.raises(RemoteUpstreamError):- parser.parse(wire([], usage=USAGE))+ parser.parse(wire([], usage={**USAGE, "total_tokens": 40}))def test_tool_calls_preserve_only_function_wire_fields() -> None:diff --git a/packages/sie_server/tests/processors/test_remote_chat.py b/packages/sie_server/tests/processors/test_remote_chat.pyindex 694942d24..aaf2973c0 100644--- a/packages/sie_server/tests/processors/test_remote_chat.py+++ b/packages/sie_server/tests/processors/test_remote_chat.py@@ -227,6 +227,35 @@ async def test_truncated_chat_never_settles_as_success(remote: tuple, missing: sassert stream.closed+def running(completion_tokens: int) -> dict:+ return {"prompt_tokens": 37, "completion_tokens": completion_tokens, "total_tokens": 37 + completion_tokens}+++async def test_running_usage_on_every_chunk_settles_on_the_last_final_usage(remote: tuple) -> None:+ frames: list[dict | str] = [+ {**choice(""), "usage": running(0)},+ {**choice(), "usage": running(1)},+ {**choice("", finish="stop"), "usage": running(1)},+ {"choices": [], "usage": USAGE},+ "[DONE]",+ ]+ respond(remote, frames=frames)+ msg, chunks = await run(remote)+ assert "".join(chunk.get("text_delta", "") for chunk in chunks) == "answer"+ assert chunks[-1]["done"]+ assert chunks[-1]["finish_reason"] == "stop"+ assert chunks[-1]["usage"] == USAGE+ msg.ack.assert_awaited_once()+++async def test_running_usage_without_a_final_usage_never_settles(remote: tuple) -> None:+ frames: list[dict | str] = [{**choice(), "usage": running(1)}, choice("", finish="stop"), "[DONE]"]+ respond(remote, frames=frames)+ _msg, chunks = await run(remote)+ assert chunks[-1]["finish_reason"] == "error"+ assert chunks[-1]["error"]["code"] == "inference_error"++async def test_cancel_closes_upstream_and_settles_once(remote: tuple) -> None:stream = respond(remote, stream=ChatStream([choice()], hold=True))task = asyncio.create_task(run(remote))