DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Beyond Django and Flask: How FastAPI Became Python's Fastest-Growing Framework for Production APIs
  • From Zero to Local AI in 10 Minutes With Ollama + Python
  • Building an AI Nutrition Coach With OpenAI, Gradio, and gTTS
  • Instant APIs With Copilot and API Logic Server

Trending

  • Python Asyncio: Understanding Concurrency With a Scraper
  • You Do Not Need a PhD to Become an AI Engineer: The Essential Skill Stack
  • RAG Architecture Patterns: Proxy, Caching, and Routing
  • A/B Testing Under Shared Constraints: Supply, Inventory, and User Attention

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Hosted Code Interpreter in Spring AI: Letting OpenAI Write and Run Python via the Responses API

Hosted Code Interpreter in Spring AI: Letting OpenAI Write and Run Python via the Responses API

Enable OpenAI's hosted Code Interpreter in Spring AI via the Responses API, then trace a real request as the model writes and runs Python server-side.

By 
Horatiu Dan
DZone Core CORE ·
Nov. 25, 26 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
129 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

LLMs are good at explaining how to compute something and surprisingly unreliable at actually computing it. Ask for an estimate that involves a division, a rounding rule, and a confidence interval, and the response will be convincing while the numbers are not quite right. The standard fix is to let the model write code and have something else execute it.

OpenAI’s hosted Code Interpreter does exactly that, inside a single API request: the model writes Python, OpenAI runs it in a sandboxed container, the printed output is fed back to the model, and the model answers using the real result. Nothing executes on our side.

Spring AI 2.1.0-RC1 adds first-class support for this capability through its new OpenAI Responses chat model. This article shows how little is needed to turn it on in a Spring Boot application and why it requires the Responses API rather than Chat Completions. Finally, it walks through a full request and response captured by a custom logging advisor, so the generated Python, its execution output, and the final answer are all visible.

The complete POC is a small command-line application. Its only job is to send one problem statement to the model and print the solution.

Setting It Up

Three things are needed: the dependency, four configuration properties, and an ordinary ChatClient.

Dependency

The project builds on Spring Boot 4.1.2 with Java 25 and imports the Spring AI BOM at version 2.1.0-RC1. The single runtime dependency is the OpenAI starter.

XML
 
<properties>
    <java.version>25</java.version>
    <spring-ai.version>2.1.0-RC1</spring-ai.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-model-openai</artifactId>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>${spring-ai.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>


Configuration

This is the whole of application.properties file. 

Properties files
 
spring.ai.openai.api-key=${OPEN_AI_API_KEY}
# use responses API
spring.ai.openai.chat.api=responses
# enable code interpreter
spring.ai.openai.responses.hosted-tools.code-interpreter.enabled=true
# readable reasoning: ask OpenAI for reasoning summaries (auto | concise | detailed)
spring.ai.openai.responses.reasoning-summary=auto
# return what the hosted code interpreter printed
spring.ai.openai.responses.include=code_interpreter_call.outputs


  • spring.ai.openai.chat.api=responses switches the auto-configured ChatModel from the Chat Completions endpoint to the Responses endpoint. With responses, Spring AI creates an OpenAiResponsesChatModel bean instead of an OpenAiChatModel.
  • spring.ai.openai.responses.hosted-tools.code-interpreter.enabled=true declares the code interpreter as a tool on every request. The property’s own description in the configuration metadata reads “Let OpenAI run Python in a sandboxed container inside the request.”
  • spring.ai.openai.responses.reasoning-summary=auto asks OpenAI to return summaries of the model’s reasoning. OpenAI never returns the raw reasoning text, so a summary is the only readable form we can get.
  • spring.ai.openai.responses.include=code_interpreter_call.outputs asks for the outputs of the interpreter run, meaning what the Python printed, to be included in the response. Without it, the response says the code ran but doesn’t carry what it produced.

The same thing can be done in code, per request, with: 

Java
 
OpenAiResponsesChatOptions.builder()
    .hostedTools(HostedTool.CodeInterpreter.of())
    .build()


The HostedTool sealed interface also types web search, file search, MCP servers and image generation, plus a Raw escape hatch for tools Spring AI does not type yet. The CodeInterpreter record takes an optional container id, exposed as spring.ai.openai.responses.hosted-tools.code-interpreter.container-id, to reuse a container across requests. 

The Client and the Problem

The service is a plain ChatClient. Nothing in it mentions tools, Python, or the Responses API. 

Java
 
@Service
public class ProblemSolver {
    private final ChatClient chatClient;
    public ProblemSolver(ChatClient.Builder chatClientBuilder) {
        chatClient = chatClientBuilder
                .defaultSystem("You are a helpful problem solver. " +
                        "Provide elegant, meaningful solutions to the requested problems.")
                .defaultAdvisors(new CustomLoggingAdvisor())
                .build();
    }
    public String solve(String problem) {
        return chatClient.prompt()
                .user(problem)
                .call()
                .content();
    }
}


A CommandLineRunner sends one problem at startup and logs the answer. The problem is a classic estimation task: how many identical objects fit in a container, given the volumes and a packing density. 

Java
 
private static final String PROBLEM = """
    Use Python to estimate the quantity of similarly shaped objects inside a container.
    Optionally report a lower and upper confidence bound based on uncertainty in the measurements.
    The program shall print the results to the console.
    
    Input:
        container_volume = 540.0      # cm^3
        object_volume = 1.25          # cm^3
        packing_density = 0.64        # between 0 and 1
    
    Output:
        estimated_count
""";


The prompt says “Use Python” and “print the results to the console.” That nudge makes the model reach for the interpreter rather than do the arithmetic in its head. 

Why the Responses API and Not Chat Completions

Chat Completions has no notion of a tool that the provider runs for you. Normally, every tool is a function the application declares, the model requests, and the application executes before sending the result back in a second round trip. Hosted tools such as code interpreter, web search, file search, and image generation exist only on the Responses API, which is where OpenAI lands new capability.

There is a harder constraint too. Starting with GPT-5.4, Chat Completions no longer supports tool calling combined with a reasoning effort other than none.

In Spring AI, flipping spring.ai.openai.chat.api to responses is enough to swap the implementation underneath the same ChatClient. The code in ProblemSolver does not change.

Hosted tools are deliberately not modelled as ToolCallbacks. There is nothing for the application to run, so their calls never surface as tool calls and never trigger the client-side tool-calling loop. Instead, each hosted tool call appears in the response transcript as its own item. A summary of them is placed on the generation metadata under the key openai.responses.hosted_tool_calls, as a list of type, id and status entries.

The request builder applies exactly three framework-level defaults, all for correctness:

  • store: false is always sent. The model is stateless by design and it is also what makes OpenAI return the encrypted reasoning blob instead of keeping it server-side.
  • include always contains reasoning.encrypted_content and anything we configure is merged with it rather than overriding it. That is why the code_interpreter_call.outputs value in our properties file is added to, not replacing, the default.
  • Function tool schemas are sent with strict: false unless told otherwise.

Everything else defers to the provider default unless set.

The CustomLoggingAdvisor

To see what actually travels over the wire in domain terms, the project registers a CallAdvisor. Advisors wrap the call to the model. This one runs at LOWEST_PRECEDENCE, so it is the innermost advisor and sees the final prompt going out and the raw ChatResponse coming back, before any other advisor touches either.

Java
 
@Override
public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
	log.info("\n{}", formatRequest(request.prompt()));

	long start = System.nanoTime();
	ChatClientResponse response = chain.nextCall(request);
	long elapsedMs = (System.nanoTime() - start) / 1_000_000;

	log.info("\n{}", formatResponse(response.chatResponse(), elapsedMs));

	return response;
}


The request side prints the model, the options class, temperature and max tokens, then each message with its type (see formatRequest()). The response side prints the elapsed time, the model that answered, the token usage, then the interesting part – the assistant message broken down into its parts (see formatResponse()).

In Spring AI 2.x an AssistantMessage is a list of MessageParts. The hierarchy is sealed, which lets the advisor classify each part with an exhaustive pattern-matching switch:

Java
 
private String category(MessagePart part) {
    return switch (part) {
        case TextPart _ -> "TEXT";
        case ReasoningPart _ -> "REASONING";
        case ToolCallPart _ -> "TOOL_CALL";
        case ToolResultPart _ -> "TOOL_RESULT";
        case MediaPart _ -> "MEDIA";
        case UnknownPart u -> "PROVIDER(" + u.kind() + ")";
    };
}


The advisor first prints the order in which the parts arrived, then groups them by category. The order matters: for the Responses API, each output item becomes exactly one part, in transcript order, so the Order: line is a faithful record of what the model did during the request.

The code interpreter call arrives as an UnknownPart. That is the type Spring AI uses for any item a server-side tool produced or any item type the SDK does not model yet.

It carries the provider (openai.responses), the item’s type as its kind and the whole item as JSON in rawJson(). The advisor parses that JSON and when it finds a code field, renders the Python and each entry of outputs:

Java
 
if (node.has("code")) {
    sb.append('\n').append("Code:\n").append(indent(node.get("code").asString(), 2));
    JsonNode outputs = node.get("outputs");
    if (outputs != null && outputs.isArray()) {
        sb.append('\n').append("Outputs (").append(outputs.size()).append("):");
        for (JsonNode output : outputs) {
            String type = output.path("type").asString("?");
            String body = output.has("logs") ? output.get("logs").asString()
                : output.has("url") ? output.get("url").asString()
                : output.toPrettyString();
            sb.append('\n').append(indent("[" + type + "]\n" + indent(body, 2), 2));
        }
    }
    return sb.toString();
}


An output of type logs is what the program printed to stdout. 

An output of type image carries a URL, which is how a plot made with matplotlib would come back. 

Reasoning parts are rendered from their summary, and the size of the opaque encrypted payload is reported rather than its content, since it is not meant to be read. 

Walking Through a Run

What follows is the advisor’s output for one real run of the application, lightly trimmed. The generated Python is about 130 lines, so only its shape is quoted. The numbers are reproduced exactly. See Resource 4 for the full version of the generated code. 

The Request

Plain Text
 
>>> REQUEST
Model:                   gpt-5-mini
Options type:            OpenAiResponsesChatOptions
Temperature:             -
Max tokens:              -
Messages:                2
[1] SYSTEM
    You are a helpful problem solver. Provide elegant, meaningful solutions to the requested problems.
[2] USER
    Use Python to estimate the quantity of similarly shaped objects inside a container.
    ...


The options class confirms the endpoint swap: an OpenAiResponsesChatOptions instance, not the Chat Completions one. No model was configured, so the framework default gpt-5-mini is used. Temperature and max tokens are unset and therefore left to the provider. 

The two messages are what the ChatClient assembled from the default system text and the user prompt. On the wire, they do not travel as a messages array. The Responses request builder puts the first system message into the top-level instructions field and the user message into the input list. The code interpreter tool is not visible here because it is not a message. It is added to the request’s tools array by the request builder from the enabled hosted tools. 

The Response Header

Plain Text
 
<<< RESPONSE (44092 ms)
Model:                   gpt-5-mini-2025-08-07
TOKENS
    Prompt (input):      3242
    Completion (output): 4081
    Total:               7323
ASSISTANT MESSAGE PARTS (3 total)
    Order: REASONING -> PROVIDER(code_interpreter_call) -> TEXT


Forty-four seconds for one call is quite a lot, but this is the honest cost of what happened:

  • The model reasoned
  • Wrote a program
  • OpenAI started a container and ran a 200,000-sample Monte Carlo simulation (Resource 3)
  • The model then wrote its answer

All of that is one HTTP request from the application’s point of view. The model name in the response is the dated snapshot that served the request.

The token figures also tell a story. Our two messages are a few hundred tokens, yet the input count is in the thousands, because a hosted tool call is a multi-step exchange on OpenAI’s side and the interpreter’s output is fed back to the model as input within the same request. The output count covers the reasoning, the generated code, and the final text.

The Order: line is the transcript. Three output items came back and became three parts in that exact order:

  • The model thought
  • Then it ran code
  • Then it answered

There was no second reasoning item after the execution. The model went straight from the interpreter’s output to its text.

The Reasoning Part

Plain Text
 
>> REASONING [1]
     #1 (part 1 of 3)
        Summary:
          **Estimating object count in containers**
          I'm tasked with creating Python code to estimate the number of similarly shaped
          objects in a container using the formula container_volume × packing_density /
          object_volume. I need to report confidence bounds based on uncertainties and use
          the first-order propagation of uncertainty. ... **Creating estimation code**
          ... **Building estimation code with options**
          I need to use `python_user_visible` to run the code and show outputs ...
          ... **Implementing Monte Carlo sampling**
          ...
        Opaque payload: provider=openai.responses, kind=encrypted_content, 11768 chars


This is what reasoning-summary=auto produces. One reasoning item carried four summary entries, which Spring AI joins into a single summary() string without a separator, which is why the bold headings run into the preceding sentence.

The summary is readable enough to see the model’s plan. The basic formula, first-order error propagation using partial derivatives and a Monte Carlo check, with the decision to demonstrate both with example uncertainties since the prompt made the bounds optional and gave none.

One detail gives away the mechanics. The model refers to a tool named python_user_visible. The reasoning is deciding to call the hosted tool.

The ReasoningPart.text() is empty because OpenAI does not return raw reasoning. What it does return is the encrypted blob, here quite a long one, held in the part’s payload.

The Code Interpreter Part

Plain Text
 
>> PROVIDER [1]
     #1 (part 2 of 3)
        Provider: openai.responses
        Kind:     code_interpreter_call
        Code:
          # Estimate number of similarly shaped objects in a container
          # Shows point estimate and optional confidence bounds (analytic propagation + Monte Carlo)
          import math
          import numpy as np
          from scipy.stats import norm
          def estimate_count(container_volume,
                             object_volume,
                             packing_density,
                             container_unc=None,
                             object_unc=None,
                             packing_unc=None,
                             ci=0.95,
                             mc_samples=200000,
                             random_seed=0):
              ...
              N = (container_volume * packing_density) / object_volume
              ...
              sigma_N_analytic = math.sqrt(
                  (dN_dVc * sigma_Vc)**2 +
                  (dN_dp  * sigma_p )**2 +
                  (dN_dvo * sigma_vo)**2
              )
              ...
              rng = np.random.default_rng(random_seed)
              ...
          container_volume = 540.0      # cm^3
          object_volume = 1.25          # cm^3
          packing_density = 0.64        # between 0 and 1
          ...
          container_unc = 5.0     # cm^3 (std dev)
          object_unc = 0.05       # cm^3 (std dev)
          packing_unc = 0.02      # absolute (std dev)
          ...
        Outputs (1):
          [logs]
            Point estimate (no uncertainties):
              estimated_count = 276.480
            Estimate with uncertainty propagation and Monte Carlo (example uncertainties):
              point estimate = 276.480
              analytic std dev (approx) = 14.266
              analytic 95% CI = (248.520, 304.440)
              Monte Carlo mean = 276.962
              Monte Carlo std dev = 14.298
              Monte Carlo 95% CI = (250.222, 306.285)
              Monte Carlo samples used = 200000


This is the part the whole setup exists for. It arrived as an UnknownPart whose kind is code_interpreter_call, the item type OpenAI assigns to a hosted interpreter run.

The advisor found the code field in the raw JSON and printed it, followed by the single logs output.

The program is a reasonable piece of engineering, not a one-liner. In the end, its execution prints both the plain estimate and the uncertainty-aware one.

The [logs] block is stdout from the container. These numbers were computed by NumPy and SciPy, not predicted by the model.

This output only came back to us because of include=code_interpreter_call.outputs. Without it, the item would still report that code ran, but the outputs array would be absent.

On the other hand, note what is empty:

Plain Text
 
>> TOOL CALLS [0]
	(none)

>> TOOL RESULTS [0]
	(none)


Nothing was asked of the JVM. No ToolCallPart was produced, no function ran locally, and Spring AI’s tool-calling loop never engaged. The entire execution happened between the model and OpenAI’s container. 

The Text Part

Plain Text
 
>> TEXT [1]
     #1 (part 3 of 3)
        I ran a short Python program that computes the estimated count and — if you provide
        measurement uncertainties — returns approximate confidence bounds using both analytic
        (first-order) uncertainty propagation and a Monte Carlo simulation.

        Point estimate:
        - estimated_count = 276.480

        Results (95% CI shown):
        - analytic 95% CI ≈ (248.520, 304.440)
        - Monte Carlo mean ≈ 276.962
        - Monte Carlo 95% CI ≈ (250.222, 306.285)

        Code (you can copy and run; change the uncertainty values or CI/confidence level as needed):
        ...


This is the string that content() returns to ProblemSolver.solve() and that the runner logs as the solution. Obviously, every figure in it matches the [logs] output perfectly, because the model wrote the answer after reading the execution result.

The final text is the only one of the three parts that a plain content() call exposes. The reasoning and the interpreter runs are present on the ChatResponse as parts and in the generation metadata, but an application has to look for them, which is exactly what the advisor does.

Takeaways

The hosted code interpreter turns “write me a program” into “run me a program” without any execution plumbing on our side. No local Python, no sandbox, no tool-calling loop. In Spring AI 2.1.0-RC1, enabling it is one property to pick the Responses endpoint and one to switch the tool on. Two more properties, for reasoning summaries and interpreter outputs, make the result readable.

The Responses model keeps the familiar ChatClient surface while exposing the richer transcript as typed message parts. A small advisor that walks those parts is the cheapest way to see what the model reasoned, what it executed, and what it concluded.

Natural next steps are reusing a container across requests through spring.ai.openai.responses.hosted-tools.code-interpreter.container-id and asking for a chart, which would come back as an image output with a URL in the same code_interpreter_call item.

Resources

[1] – Spring AI 2.1 reference, OpenAI Responses chat model

[2] – OpenAI, Code Interpreter tool guide

[3] – Monte Carlo Method

[4] – Project sample code is here.

AI API Python (language)

Published at DZone with permission of Horatiu Dan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Beyond Django and Flask: How FastAPI Became Python's Fastest-Growing Framework for Production APIs
  • From Zero to Local AI in 10 Minutes With Ollama + Python
  • Building an AI Nutrition Coach With OpenAI, Gradio, and gTTS
  • Instant APIs With Copilot and API Logic Server

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook