Deep Dive into Spring AI: Function Calling Mechanism Explained
Introduction
In previous discussions, we explored how to implement AI Agents using conventional function calling patterns. However, there's a critical aspect that deserves deeper exploration: enabling the large language model to determine whether to invoke a function while allowing the client—not Spring AI—to handle the actual function execution internally.
Understanding Function Calling in Spring AI
Function calling represents a fundamental building block in AI Agent development, enabling AI systems to interact with external systems, databases, and services. This capability significantly enhances the flexibility and usefulness of AI applications. Working with function-calling-capable chat models in Spring AI simplifies this process considerably.
Core Implementation
The core logic for handling function calls in Spring AI involves the following mechanism:
if (!isProxyToolCalls(prompt, this.defaultOptions)
&& isToolCall(response, Set.of(OpenAiApi.ChatCompletionFinishReason.TOOL_CALLS.name(),
OpenAiApi.ChatCompletionFinishReason.STOP.name()))) {
var toolCallConversation = handleToolCalls(prompt, response);
return this.internalCall(new Prompt(toolCallConversation, prompt.getOptions()), response);
}
Consider a scenario where you've integrated a weather查询 function. When a user asks about weather conditions in a specific city, the LLM automatically identifies and selects the appropriate function to invoke. During this process, the handleToolCalls method utilizes reflection to dynamically invoke the correct function, subsequently calling the internalCall method to continue processing.
Tool Call Detection
The detection mechanism validates whether the LLM's response contains valid function calls:
protected boolean isToolCall(Generation generation, Set<string> toolCallFinishReasons) {
var finishReason = (generation.getMetadata().getFinishReason() != null)
? generation.getMetadata().getFinishReason() : "";
return generation.getOutput().hasToolCalls() && toolCallFinishReasons.stream()
.map(s -> s.toLowerCase())
.toList()
.contains(finishReason.toLowerCase());
}</string>
The core logic determines whether the response from the LLM contains proper tool calls by checking both the presence of tool calls and the finish reason.
Customizing Tool Call Detection
Different LLM providers may return different response formats. For instance, when working with MiniMax, the detection method can be overridden:
protected boolean isToolCall(Generation generation, Set<string> toolCallFinishReasons) {
if (!super.isToolCall(generation, toolCallFinishReasons)) {
return false;
}
return generation.getOutput()
.getToolCalls()
.stream()
.anyMatch(toolCall -> org.springframework.ai.minimax.api.MiniMaxApiConstants.TOOL_CALL_FUNCTION_TYPE
.equals(toolCall.type()));
}</string>
This extended check verifies that the tool call type is specifically "function," since some providers support multiple tool types like web_search.
Function Auto-Execution Toggle
The default behavior of automatically calling functions and invoking the LLM again for refinement stems from the isProxyToolCalls parameter, which defaults to false. This parameter acts as a control switch determining whether the user handles logic manually or Spring AI processes it automatically.
Enable client-side function handling by configuring the options:
OpenAiChatOptions openAiChatOptions = OpenAiChatOptions.builder()
.withProxyToolCalls(true)
.build();
Once this flag is enabled, you must handle the function execution yourself. The LLM will return only the function arguments and its reasoning output.
Client-Side Function Handling
After enabling the proxy mode, you can manually process function calls:
ChatResponse content = this.chatClient
.prompt(systemPrompt)
.user(userInput)
.options(openAiChatOptions)
.advisors(messageChatMemoryAdvisor, myLoggerAdvisor)
.functions("CurrentWeather", "TravelPlanning", "toDoListFunctionWithContext", "myWorkFlowServiceCall")
.call();
Once you obtain a ChatResponse instance, you can freely manipulate the results. Reference implementations from OpenAI's test examples can significantly simplify development:
FunctionCallback weatherFunctionDef = new FunctionCallingHelper.FunctionDefinition(
"fetchWeatherData",
"Retrieve current weather information for a specified location",
"""
{
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["C", "F"]
}
},
"required": ["location", "unit"]
}
""");
@Autowired
private OpenAiChatModel chatModel;
private FunctionCallingHelper functionCallingHelper = new FunctionCallingHelper();
private static Map<String, String> parseFunctionArguments(String rawArguments) {
try {
return new ObjectMapper().readValue(rawArguments, Map.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
// Function executed by the AI model
private String fetchWeatherData(String location, String unit) {
double temperature = 0;
if (location.contains("Paris")) {
temperature = 15;
} else if (location.contains("Tokyo")) {
temperature = 10;
} else if (location.contains("San Francisco")) {
temperature = 30;
}
return String.format("The weather in %s is %s%s", location, temperature, unit);
}
void handleFunctionInvocations() throws JsonMappingException, JsonProcessingException {
List<Message> conversationHistory = List.of(
new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"));
var promptOptions = OpenAiChatOptions.builder()
.functionCallbacks(List.of(this.weatherFunctionDef))
.build();
var prompt = new Prompt(conversationHistory, promptOptions);
boolean hasToolCall = false;
ChatResponse chatResponse = null;
do {
chatResponse = this.chatModel.call(prompt);
hasToolCall = this.functionCallingHelper.isToolCall(chatResponse,
Set.of(OpenAiApi.ChatCompletionFinishReason.TOOL_CALLS.name(),
OpenAiApi.ChatCompletionFinishReason.STOP.name()));
if (hasToolCall) {
Optional<Generation> toolCallGeneration = chatResponse.getResults()
.stream()
.filter(g -> !CollectionUtils.isEmpty(g.getOutput().getToolCalls()))
.findFirst();
AssistantMessage assistantMessage = toolCallGeneration.get().getOutput();
List<ToolResponseMessage.ToolResponse> toolResponses = new ArrayList<>();
for (AssistantMessage.ToolCall toolCall : assistantMessage.getToolCalls()) {
var functionName = toolCall.name();
String functionArguments = toolCall.arguments();
Map<String, String> argumentsMap = parseFunctionArguments(functionArguments);
String functionResult = fetchWeatherData(
argumentsMap.get("location").toString(),
argumentsMap.get("unit").toString());
toolResponses.add(new ToolResponseMessage.ToolResponse(
toolCall.id(),
functionName,
ModelOptionsUtils.toJsonString(functionResult)));
}
ToolResponseMessage toolMessageResponse = new ToolResponseMessage(toolResponses, Map.of());
List<Message> toolCallConversation = this.functionCallingHelper
.buildToolCallConversation(prompt.getInstructions(), assistantMessage, toolMessageResponse);
prompt = new Prompt(toolCallConversation, promptOptions);
}
} while (hasToolCall);
logger.info("Response: {}", chatResponse);
}
This implementation uses a while loop to handle the default LLM refinement process. You can modify this approach to directly invoke your own functions, bypassing the LLM's refinement and returning results directly to the client—similar to capabilities offered by most AI agent platforms.
Conversation History Management
Critical considerations for maintaining conversation history include actively encapsulating and updating the historical chat records after each function execution. Failure to maintain proper order and format will result in errors. The standard workflow should follow this sequence:
The test examples demonstrate this operation through the buildToolCallConversation method, which implements the core logic:
protected List<Message> buildToolCallConversation(
List<Message> previousMessages,
AssistantMessage assistantMessage,
ToolResponseMessage toolResponseMessage) {
List<Message> messages = new ArrayList<>(previousMessages);
messages.add(assistantMessage);
messages.add(toolResponseMessage);
return messages;
}