MetaGPT icon indicating copy to clipboard operation
MetaGPT copied to clipboard

TypeError: openai.types.completion_usage.CompletionUsage() argument after ** must be a mapping, not NoneType

Open 2645283289 opened this issue 9 months ago • 1 comments

运行代码之后报了下面的错误 TypeError: openai.types.completion_usage.CompletionUsage() argument after ** must be a mapping, not NoneType 我从代码中定位到这部分

async for chunk in response:
            chunk_message = chunk.choices[0].delta.content or "" if chunk.choices else ""  # extract the message
            finish_reason = (
                chunk.choices[0].finish_reason if chunk.choices and hasattr(chunk.choices[0], "finish_reason") else None
            )
            log_llm_stream(chunk_message)
            collected_messages.append(chunk_message)
            if finish_reason:
                if hasattr(chunk, "usage"):
                    # Some services have usage as an attribute of the chunk, such as Fireworks
                    usage = CompletionUsage(**chunk.usage)
                elif hasattr(chunk.choices[0], "usage"):
                    # The usage of some services is an attribute of chunk.choices[0], such as Moonshot
                    usage = CompletionUsage(**chunk.choices[0].usage)

我试着将chunk打印查看返回的信息,但是我看到返回的usage均为none,我想知道我应该如何修复这个bug,以及usage的作用是什么

2645283289 avatar Mar 08 '25 04:03 2645283289

遇到一样的问题

WTHSBG avatar Mar 08 '25 18:03 WTHSBG

我已经解决了这个问题,只需要判断usage是否不为none即可,但是打印出来的usage均为none有些奇怪,修改后的代码如下

if finish_reason:
    if hasattr(chunk, "usage") and chunk.usage:
        # Some services have usage as an attribute of the chunk, such as Fireworks
        usage = CompletionUsage(**chunk.usage)
    elif hasattr(chunk.choices[0], "usage") and chunk.choices[0].usage:
        # The usage of some services is an attribute of chunk.choices[0], such as Moonshot
        usage = CompletionUsage(**chunk.choices[0].usage)

2645283289 avatar Mar 09 '25 09:03 2645283289