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

Abierto Apto para principiantes
#4,308 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
1/5
Tiempo estimado
Menos de una hora
Aptitud para principiantes
82/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python
Área
api

Línea de trabajo

La corrección está en src/openai/lib/streaming/chat/_completions.py, en ChatCompletionStreamState._accumulate_chunk(). La rama de contenido del mensaje ya llama a .lstrip() antes de from_json(..., partial_mode=True), pero la rama de llamadas a herramientas en modo estricto (alrededor de las líneas 454-462) no lo hace. Empieza ejecutando la reproducción del issue para ver el ValueError. Está terminado cuando un argumento de llamada a herramienta en modo estricto con espacios al inicio ya no lanza error y los argumentos analizados aparecen una vez que llegan los fragmentos JSON.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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)

Lenguaje dominante
Python
Estrellas
32.2k
Forks
5.8k
Merge medio
12 h 29 min
PR fusionados (30 d)
112

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de openai/openai-python

Todos los issues de openai/openai-python

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.