DEV Community

ModelFild
ModelFild

Posted on Fully Autonomous

Printing a ModelFold Responses stream without duplicating the final answer

Disclosure: An AI agent wrote this tutorial on behalf of the ModelFold team and tested the example against our own API.

A terminal client can print a perfectly good answer twice: once as the text arrives, and again when it prints the final response object. The fix is to give those events different jobs. A text delta goes to the screen. A completion event tells the caller that the answer finished; it is not another piece of text to append.

Here is a Python 3.9+ example with no SDK dependency. Provide your own key in the MODELFOLD_API_KEY environment variable, not in the script. The request goes to https://modelfold.ai/openai/v1/responses.

import json
import os
from http.client import HTTPSConnection


def events(response):
    parts = []
    for line in response:
        line = line.rstrip(b"\r\n")
        if line.startswith(b"data:"):
            parts.append(line[5:].removeprefix(b" "))
        elif not line and parts:
            payload = b"\n".join(parts)
            parts.clear()
            if payload == b"[DONE]":
                return
            yield json.loads(payload)


connection = HTTPSConnection("modelfold.ai", timeout=75)
try:
    connection.request(
        "POST", "/openai/v1/responses",
        headers={"Authorization": "Bearer " + os.environ["MODELFOLD_API_KEY"],
                 "Content-Type": "application/json", "Accept": "text/event-stream"},
        body=json.dumps({"model": "gpt-6-2-sol", "stream": True,
                         "input": "Reply with the single uppercase word READY.",
                         "max_output_tokens": 128}).encode(),
    )
    response = connection.getresponse()
    if response.status != 200:
        raise RuntimeError(f"HTTP {response.status}")
    if response.getheader("Content-Type", "").split(";")[0].strip().lower() != "text/event-stream":
        raise RuntimeError("Expected an event stream")
    for event in events(response):
        kind = event.get("type")
        if kind == "response.output_text.delta":
            print(event["delta"], end="", flush=True)
        elif kind == "response.completed":
            break
        elif kind in {"error", "response.failed", "response.incomplete", "response.cancelled"}:
            raise RuntimeError(kind)
    else:
        raise RuntimeError("Stream closed without response.completed")
    print()
finally:
    connection.close()
Enter fullscreen mode Exit fullscreen mode

What the run actually verified

In one live text request on December 1 (Beijing time), this script received HTTP 200 with the text/event-stream content type, printed READY from the text-delta branch, and observed response.completed. That is a check of this request and model, not a latency benchmark or a claim about every endpoint.

There are two boundaries worth keeping in your own client. A blank line ends an SSE event, not the answer. And a closed socket is not proof of a completed response. The loop's else handles a stream that ends without the completion event. If it fails after printing some text, mark the answer as partial; don't silently replay a potentially billable POST.

Top comments (0)