chat.completions.stream() crashes with ValueError: EOF while parsing a value on leading whitespace in strict function tool call arguments

Aberta Para iniciantes
#4,308 1 comentário 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
1/5
Tempo estimado
Menos de uma hora
Facilidade para iniciantes
82/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
python
Domínio
api

Direção de pesquisa

A correção está em src/openai/lib/streaming/chat/_completions.py, em ChatCompletionStreamState._accumulate_chunk(). O ramo de conteúdo da mensagem já chama .lstrip() antes de from_json(..., partial_mode=True), mas o ramo de chamadas de ferramenta em modo strict (por volta das linhas 454-462) não chama. Comece executando a reprodução do issue para ver o ValueError. Está concluído quando um argumento de chamada de ferramenta em modo strict com espaços no início não gera mais erro e os argumentos analisados aparecem assim que os chunks JSON chegam.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

Confirm this is an issue with the Python library and not an underlying OpenAI API
  • This is an issue with the Python library
Describe the bug

In src/openai/lib/streaming/chat/_completions.py, ChatCompletionStreamState._accumulate_chunk() already guards partial JSON parsing of message.content against whitespace-only prefixes (added for #2082):

if (
    choice_snapshot.message.content
    and not choice_snapshot.message.refusal
    and is_given(self._rich_response_format)
    # partial parsing fails on white-space
    and choice_snapshot.message.content.lstrip()
):
    choice_snapshot.message.parsed = from_json(
        bytes(choice_snapshot.message.content, "utf-8"),
        partial_mode=True,
    )

However, 18 lines below (lines 454-462), the sibling from_json(..., partial_mode=True) call for strict function tool call arguments omits .lstrip():

if (
    input_tool
    and input_tool.get("function", {}).get("strict")
    and tool_call_snapshot.function.arguments
):
    tool_call_snapshot.function.parsed_arguments = from_json(
        bytes(tool_call_snapshot.function.arguments, "utf-8"),
        partial_mode=True,
    )

If a streamed strict tool call begins with a whitespace chunk (such as " " or "\n"), jiter.from_json(b" ", partial_mode=True) immediately raises ValueError: EOF while parsing a value at line 1 column 1, aborting the stream before the JSON payload chunks arrive.

To Reproduce
  1. Create a ChatCompletionStreamState (or client.chat.completions.stream()) with a strict tool (e.g., pydantic_function_tool(GetWeather)).
  2. Feed an initial role chunk followed by a tool call delta whose arguments starts with " " or "\n".
  3. Observe ValueError: EOF while parsing a value at line 1 column 1.
Code snippets
from pydantic import BaseModel
from openai import pydantic_function_tool
from openai.lib.streaming.chat import ChatCompletionStreamState
from openai.types.chat import ChatCompletionChunk

class GetWeather(BaseModel):
    city: str

state = ChatCompletionStreamState(input_tools=[pydantic_function_tool(GetWeather)])
state.handle_chunk(
    ChatCompletionChunk.model_validate(
        {
            "id": "chatcmpl-1",
            "object": "chat.completion.chunk",
            "created": 1,
            "model": "gpt-4o",
            "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}],
        }
    )
)
state.handle_chunk(
    ChatCompletionChunk.model_validate(
        {
            "id": "chatcmpl-1",
            "object": "chat.completion.chunk",
            "created": 1,
            "model": "gpt-4o",
            "choices": [
                {
                    "index": 0,
                    "delta": {
                        "tool_calls": [
                            {
                                "index": 0,
                                "id": "call_1",
                                "type": "function",
                                "function": {"name": "GetWeather", "arguments": " "},
                            }
                        ]
                    },
                    "finish_reason": None,
                }
            ],
        }
    )
)
# ValueError: EOF while parsing a value at line 1 column 1

Suggested fix in src/openai/lib/streaming/chat/_completions.py:

                     if (
                         input_tool
                         and input_tool.get("function", {}).get("strict")
                         and tool_call_snapshot.function.arguments
+                        # partial parsing fails on white-space
+                        and tool_call_snapshot.function.arguments.lstrip()
                     ):
OS

macOS

Python version

Python 3.14

Library version

openai v3.57.0 (main@f63f14b)

Linguagem predominante
Python
Estrelas
32.2k
Forks
5.8k
Merge médio
12h 29min
PRs com merge (30d)
112

Preparar o ambiente

Abrir no Codespaces

Inicia o contêiner de desenvolvimento do projeto no navegador, com a sua própria conta do GitHub.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de openai/openai-python

Todas as issues de openai/openai-python

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.