Files
semantic-kernel/python/tests
Evan Mattson 4b23389f71 Python: Emit token usage with streaming chat completion agent. (#12416)
### Motivation and Context

The chat completion agent was not emitting token using during streaming
invocation because we were only allowing through `response.items`. In
the case of token usage, `response.items` is [] and the usage is
contained as part of the message's `metadata` dict. This PR fixes that
bug and allows for `response.items or response.metadata.get("usage")`.
Two new samples are added to the concepts/agents/chat_completion dir to
show how one can track token use for streaming and non-streaming agent
invocation. Token usage handling is also added to the chat completion
agent integration tests.

<!-- Thank you for your contribution to the semantic-kernel repo!
Please help reviewers and future users, providing the following
information:
  1. Why is this change required?
  2. What problem does it solve?
  3. What scenario does it contribute to?
  4. If it fixes an open issue, please link to the issue here.
-->

### Description

- Fixes a bug where we weren't emitting the streaming token usage for
the chat completion agent. Also now includes the `prompt_tokens_details`
and `completion_tokens_details` models that are returned, but not
previously handled.
- Adds new samples
- Updates integration tests to track token usage and make sure they're
non-zero.
- Closes #12411

<!-- Describe your changes, the overall approach, the underlying design.
These notes will help understanding how your code works. Thanks! -->

### Contribution Checklist

<!-- Before submitting this PR, please make sure: -->

- [X] The code builds clean without any errors or warnings
- [X] The PR follows the [SK Contribution
Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md)
and the [pre-submission formatting
script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts)
raises no violations
- [X] All unit tests pass, and I have added new tests where possible
- [X] I didn't break anyone 😄
2025-06-09 23:12:05 +00:00
..
2023-04-13 16:12:36 -07:00