crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] OpenAI streaming skips text, tool deltas and finish_reason on chunks with usage

Open suqinghen opened this issue 1 month ago • 3 comments

Description

The native OpenAICompletion Chat Completions streaming handlers unconditionally continue after extracting a chunk's usage. They therefore skip any choices in the same chunk, including text, tool-call deltas, and finish_reason.

Consequences depend on the terminal chunk:

  • A final text delta carrying usage is silently omitted from the returned answer.
  • If all text is in that chunk, the handler returns an empty string.
  • A final tool-call delta carrying usage can lose the end of its arguments.
  • A chunk with an empty text delta, usage, and finish_reason="stop" preserves the text accumulated earlier but loses the finish reason.
  • The async response_model branch also skips such chunks, so a JSON suffix in a mixed chunk is lost before validation.

This report concerns native Chat Completions, rather than the Responses API.

Affected versions and source

The minimal synchronous example below was reproduced with CrewAI 1.15.20. The same behavior was confirmed by isolated execution of the unmodified streaming/finalization methods from release 1.15.33 and main at 90266d5257055e05fabeced6d848eda8d0280cbf.

All three unconditional skips remain in 1.15.33:

Steps to reproduce

Run the following deterministic example with CrewAI installed. It uses synthetic OpenAI SDK chunks and a stub client. It makes no network requests and needs no real API key, provider account, or external configuration. Calling the handler directly isolates the stream-consumption bug from agent retry behavior.

from types import SimpleNamespace
from unittest.mock import patch

from crewai.llms.providers.openai.completion import OpenAICompletion
from openai.types.chat import ChatCompletionChunk


def chunk(text, *, with_usage=False, finish_reason=None):
    return ChatCompletionChunk.model_validate({
        'id': 'example',
        'object': 'chat.completion.chunk',
        'created': 0,
        'model': 'example-model',
        'choices': [{
            'index': 0,
            'delta': {'content': text},
            'finish_reason': finish_reason,
        }],
        'usage': {
            'prompt_tokens': 1,
            'completion_tokens': 2,
            'total_tokens': 3,
        } if with_usage else None,
    })


cases = {
    'text + usage': [
        chunk('HELLO-'),
        chunk('END', with_usage=True, finish_reason='stop'),
    ],
    'only text chunk + usage': [
        chunk('HELLO-END', with_usage=True, finish_reason='stop'),
    ],
    'empty delta + usage + finish_reason': [
        chunk('HELLO-END'),
        chunk('', with_usage=True, finish_reason='stop'),
    ],
}

for name, chunks in cases.items():
    llm = OpenAICompletion(model='example-model', api_key='unused', stream=True)
    client = SimpleNamespace(chat=SimpleNamespace(
        completions=SimpleNamespace(create=lambda **_: iter(chunks))
    ))
    with (
        patch.object(OpenAICompletion, '_get_sync_client', return_value=client),
        patch.object(OpenAICompletion, '_emit_stream_chunk_event'),
        patch.object(OpenAICompletion, '_emit_call_completed_event') as completed,
    ):
        result = llm._handle_streaming_completion({'messages': []})
    finish = completed.call_args.kwargs['finish_reason']
    print(f'{name}: result={result!r}, finish_reason={finish!r}')

Actual behavior

text + usage: result='HELLO-', finish_reason=None
only text chunk + usage: result='', finish_reason=None
empty delta + usage + finish_reason: result='HELLO-END', finish_reason=None

Expected behavior

All three cases should return HELLO-END and preserve finish_reason='stop'. Usage should still be recorded once.

A separate usage-only chunk with choices=[] should continue to work as before.

Public protocol context

The DeepSeek Chat Completions documentation specifies a terminal chunk containing usage and one choice with no new content and a non-null finish reason. This is sufficient to expose the finish-reason loss even when no text is dropped. That documentation also specifies that terminal usage is returned when include_usage is false or omitted, so disabling that option does not eliminate the finish-reason issue.

The text-loss cases above are synthetic compatibility fixtures; they do not claim that the official OpenAI or DeepSeek API emits a non-empty text delta together with usage.

Possible solution

Process usage and choices independently in all three branches: extract usage when present, then continue with choice processing whenever choices are present. Only skip choice processing when choices is empty.

 if getattr(chunk, "usage", None):
     usage_data = self._extract_openai_token_usage(chunk)
-    continue

 if not chunk.choices:
     continue

Regression coverage should include sync/async text, a single text chunk, terminal finish reasons with empty text, tool-argument suffixes, async structured output, and the separate choices=[] usage-only control. Assert both output preservation and token accounting.

Additional context

The reproduction is independent of deployment and operating-system details and does not require crewai-tools.

AI-assisted report. Maintainer action requested: apply the llm-generated label required by the contributing guidelines.

suqinghen avatar Oct 29 '26 13:10 suqinghen

I'll fix this: handle usage and choices independently in the sync and both async streaming paths, with regression tests. PR to follow shortly.

2SinceJuly avatar Oct 29 '26 13:10 2SinceJuly

Fixed in #8776: the streaming handlers no longer drop the choices of chunks that also carry usage. (Could not add the llm-generated label - no triage permission on this repo.)

2SinceJuly avatar Oct 29 '26 13:10 2SinceJuly

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Nov 29 '26 12:11 github-actions[bot]