Skip to content

fix(chat): return the completion when a chat response has no usage - #503

Merged
ASuresh0524 merged 2 commits into
StarTrail-org:mainfrom
tushar-mahalya:fix/chat-usage-optional
Dec 3, 2026
Merged

ASuresh0524 merged 2 commits into
StarTrail-org:mainfrom
tushar-mahalya:fix/chat-usage-optional

Conversation

@tushar-mahalya

Copy link
Copy Markdown
Contributor

What does this PR do?

In the OpenAI SDK (ChatCompletion.usage), usage is Optional[CompletionUsage], so a valid chat completion doesn't have to include it. Right now OpenAIChat, MiniMaxChat, NovitaChat, AtlasCloudChat, and LiteLLMChat all read response.usage.total_tokens inside the same try block as the request, so when usage is missing the AttributeError gets caught by the generic except Exception and ask() returns "Error: Could not get a response from ..." instead of the actual reply. Under leann react, that string has no Action: in it, so ReActAgent hands it back as the final answer.

Minimal reproducer using the real openai client over an httpx.MockTransport:

import httpx, openai
from leann.chat import OpenAIChat

def handler(req):
    return httpx.Response(200, json={
        "id": "x", "object": "chat.completion", "created": 1, "model": "m",
        "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "The answer is 42."}}],
    })

c = OpenAIChat(model="gpt-4o", api_key="k", base_url="http://local.invalid/v1")
c.client = openai.OpenAI(api_key="k", base_url="http://local.invalid/v1", http_client=httpx.Client(transport=httpx.MockTransport(handler)))
print(repr(c.ask("q")))

On main (494ef3c):

"Error: Could not get a response from OpenAI. Details: 'NoneType' object has no attribute 'total_tokens'"

With this PR:

'The answer is 42.'

Since that token-logging line was added separately across each provider (#147, #282, #294, #388, #395), I moved it into one _report_token_usage(usage, emit) helper in chat.py that returns early when usage is None. Each caller passes its own emitter (print for OpenAI, MiniMax, and LiteLLM; logger.info for Novita and Atlas Cloud) so nothing binds print at import time. AnthropicChat has a different, required usage shape and is untouched.

The new tests in tests/test_chat_missing_usage.py exercise the real openai client against httpx.MockTransport for missing usage (four providers) and normal usage printing/logging (including a runtime-patched print), and tests/test_litellm_provider.py covers both cases against the existing LiteLLM stub.

Related Issues

No existing issue found (checked open/closed issues and PRs for usage / total_tokens; #498 only touches max_completion_tokens).

Checklist

  • Tests pass: the new and touched provider tests pass (35 passed, 1 skipped). The full suite (python -m pytest tests, excluding test_embedding_server_manager_e2e.py) has 14 failures and 2 collection errors on both main and this branch with identical node ids, mostly from the ivf/diskann backends not being installed locally.
  • Code formatted (ruff format and ruff check on the changed files)
  • Pre-commit hooks pass (pre-commit run --from-ref upstream/main --to-ref HEAD)

@ASuresh0524
ASuresh0524 merged commit b05d228 into StarTrail-org:main Dec 3, 2026
31 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.

2 participants