Skip to content

completion_tokens return None when result.usage is None #6352

@alejandroabdel

Description

@alejandroabdel

What happened?

Describe the bug
For something reason when I use _model_client.create genereted of next bug :
--- Logging error ---
Traceback (most recent call last):
File "C:\Users\anis.abdel\AI\seraph3\utils\llm_usage.py", line 34, in emit
self._completion_tokens += event.completion_tokens
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'

I explored that situation and I founded the reason:

usage = RequestUsage(
            # TODO backup token counting
            prompt_tokens=result.usage.prompt_tokens if result.usage is not None else 0,
            completion_tokens=(result.usage.completion_tokens if result.usage is not None else 0),
        )

        logger.info(
            LLMCallEvent(
                messages=cast(List[Dict[str, Any]], create_params.messages),
                response=result.model_dump(),
                prompt_tokens=usage.prompt_tokens,
                completion_tokens=usage.completion_tokens,
            )
        )

Then completion_tokens=(result.usage.completion_tokens if result.usage is not None else 0),
return None!!!

But result.usage is None, for some reason return None but the real answer is 0.

I tried change the line 629 for the next:
(result.usage.completion_tokens if result.usage is not None and not type(None) else 0)

And the answer is sucessfully.

To Reproduce
Use OpenAI Model 4.1
Python 3.12
await self._model_client.create( ...)

Expected behavior
Succesfull comparative:
completion_tokens=(result.usage.completion_tokens if result.usage is not None else 0)
When result.usage is Not None the correct return is 0.

Screenshots
If applicable, add screenshots to help explain your problem.

Additional context
Add any other context about the problem here.

Which packages was the bug in?

Python Extensions (autogen-ext)

AutoGen library version.

Python 0.5.3

Other library version.

No response

Model used

gpt-4.1-2025-04-14

Model provider

OpenAI

Other model provider

No response

Python version

3.12

.NET version

None

Operating system

Windows

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions