spring-projects/spring-ai · error · OpenAIIoException
Failed to write request body
Error message
Failed to write request body
What it means
Wraps an IOException thrown while streaming the request body into the OkHttp sink inside SpringAiOpenAiHttpClient's repeatable request-body writer; the outbound HTTP request could not be fully written (broken pipe, connection reset, or sink failure).
Source
Thrown at models/spring-ai-openai/src/main/java/org/springframework/ai/openai/http/okhttp/SpringAiOpenAiHttpClient.java:377
@Override
public long contentLength() {
return length;
}
@Override
public boolean repeatable() {
return !isOneShot;
}
@Override
public void writeTo(OutputStream outputStream) {
BufferedSink sink = Okio.buffer(Okio.sink(outputStream));
try {
source.writeTo(sink);
sink.flush();
}
catch (IOException e) {
throw new OpenAIIoException("Failed to write request body", e);
}
}
@Override
public void close() {
}
};
}
private static Headers toOpenAiHeaders(okhttp3.Headers okHttpHeaders) {
Headers.Builder builder = Headers.builder();
for (int i = 0, n = okHttpHeaders.size(); i < n; i++) {
builder.put(okHttpHeaders.name(i), okHttpHeaders.value(i));
}
return builder.build();
}
/**View on GitHub (pinned to 98a7beda4f)
Solutions
- Retry the request; a mid-write connection reset is usually transient.
- Check that the body's source stream is not shared or concurrently closed.
- Increase write/read timeouts for large uploads and inspect the cause chain.
Example fix
int attempts = 0;
while (true) {
try { return client.execute(request, options); }
catch (OpenAIIoException e) {
if (++attempts >= 3 || e.getCause() == null) throw e;
Thread.sleep(500L * attempts);
}
} Defensive patterns
Strategy: retry
Try / catch
try {
return client.execute(request, options);
} catch (OpenAIIoException e) {
if (e.getMessage().contains("write request body")) {
// transient mid-write failure: retry with backoff, else surface
}
throw e;
} Prevention
- Retry idempotent requests after mid-write IO failures
- Avoid sharing the body stream across threads
- Increase timeouts for large uploads (images/audio)
- Keep the source stream open until the call completes
When it happens
Trigger: OkHttp serializing the request body to the network when the underlying source throws IOException — connection dropped mid-write, source stream read error, or sink closed unexpectedly (SpringAiOpenAiHttpClient.java:377).
Common situations: Uploading large payloads (long audio/images) over an unstable connection, a body stream supplied by another thread that gets closed, or read timeouts during upload.
Related errors
- Request failed
- Could not read content length
- Request failed
- Failed to write request body
- Failed to read audio speech response
AI-assisted analysis of spring-projects/spring-ai@98a7beda4f (2026-09-11).
Data as JSON: /api/errors/7ec5f9dab10c3f42.
Report an issue: GitHub.