Skip to content

Enhance top-level tool/function calling doc #1527

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
230 changes: 228 additions & 2 deletions spring-ai-docs/src/main/antora/modules/ROOT/pages/api/functions.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

The integration of function support in AI models, permits the model to request the execution of client-side functions, thereby accessing necessary information or performing tasks dynamically as required.

image::function-calling-basic-flow.jpg[Function calling, width=700, align="center"]

Spring AI currently supports function invocation for the following AI Models:

* Anthropic Claude: Refer to the xref:api/chat/functions/anthropic-chat-functions.adoc[Anthropic Claude function invocation docs].
Expand All @@ -16,3 +14,231 @@ Spring AI currently supports function invocation for the following AI Models:
* Ollama: Refer to the xref:api/chat/functions/ollama-chat-functions.adoc[Ollama function invocation docs] (streaming not supported yet).
* OpenAI: Refer to the xref:api/chat/functions/openai-chat-functions.adoc[OpenAI function invocation docs].
// * ZhiPu AI : Refer to the xref:api/chat/functions/zhipuai-chat-functions.adoc[ZhiPu AI function invocation docs].

image::function-calling-basic-flow.jpg[Function calling, width=700, align="center"]

You can register custom Java functions with the `ChatClient` and have the AI model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
This allows you to connect the LLM capabilities with external tools and APIs.
The AI models are trained to detect when a function should be called and to respond with JSON that adheres to the function signature.

The API does not call the function directly; instead, the model generates JSON that you can use to call the function in your code and return the result back to the model to complete the conversation.

Spring AI provides flexible and user-friendly ways to register and call custom functions.
In general, the custom functions need to provide a function `name`, `description`, and the function call `signature` (as JSON schema) to let the model know what arguments the function expects. The `description` helps the model to understand when to call the function.

As a developer, you need to implement a function that takes the function call arguments sent from the AI model, and responds with the result back to the model. Your function can in turn invoke other 3rd party services to provide the results.

Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatClient`.

Under the hood, Spring wraps your POJO (the function) with the appropriate adapter code that enables interaction with the AI Model, saving you from writing tedious boilerplate code.
The basis of the underlying infrastructure is the link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallback.java[FunctionCallback.java] interface and the companion link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallbackWrapper.java[FunctionCallbackWrapper.java] utility class to simplify the implementation and registration of Java callback functions.

== How it works

Suppose we want the AI model to respond with information that it does not have, for example, the current temperature at a given location.

We can provide the AI model with metadata about our own functions that it can use to retrieve that information as it processes your prompt.

For example, if during the processing of a prompt, the AI Model determines that it needs additional information about the temperature in a given location, it will start a server-side generated request/response interaction. The AI Model invokes a client side function.
The AI Model provides method invocation details as JSON, and it is the responsibility of the client to execute that function and return the response.

Spring AI greatly simplifies the code you need to write to support function invocation.
It brokers the function invocation conversation for you.
You can simply provide your function definition as a `@Bean` and then provide the bean name of the function in your prompt options.
You can also reference multiple function bean names in your prompt.

== Quick Start

Let's create a chatbot that answer questions by calling our own function.
To support the response of the chatbot, we will register our own function that takes a location and returns the current weather in that location.

When the model needs to answer a question such as `"What’s the weather like in Boston?"` the AI model will invoke the client providing the location value as an argument to be passed to the function. This RPC-like data is passed as JSON.

Our function calls some SaaS-based weather service API and returns the weather response back to the model to complete the conversation. In this example, we will use a simple implementation named `MockWeatherService` that hard-codes the temperature for various locations.

The following `MockWeatherService.java` represents the weather service API:

[source,java]
----
public class MockWeatherService implements Function<Request, Response> {

public enum Unit { C, F }
public record Request(String location, Unit unit) {}
public record Response(double temp, Unit unit) {}

public Response apply(Request request) {
return new Response(30.0, Unit.C);
}
}
----

=== Registering Functions as Beans

Spring AI provides multiple ways to register custom functions as beans in the Spring context.

We start by describing the most POJO-friendly options.

==== Plain Java Functions

In this approach, you define a `@Bean` in your application context as you would any other Spring managed object.

Internally, Spring AI `ChatModel` will create an instance of a `FunctionCallbackWrapper` that adds the logic for it being invoked via the AI model.
The name of the `@Bean` is used function name.

[source,java]
----
@Configuration
static class Config {

@Bean
@Description("Get the weather in location") // function description
public Function<MockWeatherService.Request, MockWeatherService.Response> currentWeather() {
return new MockWeatherService();
}

}
----

The `@Description` annotation is optional and provides a function description that helps the model understand when to call the function. It is an important property to set to help the AI model determine what client side function to invoke.

Another option for providing the description of the function is to use the `@JsonClassDescription` annotation on the `MockWeatherService.Request`:

[source,java]
----
@Configuration
static class Config {
@Bean
public Function<Request, Response> currentWeather() { // bean name as function name
return new MockWeatherService();
}
}

@JsonClassDescription("Get the weather in location") // // function description
public record Request(String location, Unit unit) {}
----

It is a best practice to annotate the request object with information such that the generated JSON schema of that function is as descriptive as possible to help the AI model pick the correct function to invoke.

==== FunctionCallback Wrapper

Another way to register a function is to create a `FunctionCallbackWrapper` like this:

[source,java]
----
@Configuration
static class Config {

@Bean
public FunctionCallback weatherFunctionInfo() {

return FunctionCallbackWrapper.builder(new MockWeatherService())
.withName("CurrentWeather") // (1) function name
.withDescription("Get the weather in location") // (2) function description
.build();
}
}
----

It wraps the 3rd party `MockWeatherService` function and registers it as a `CurrentWeather` function with the `ChatClient`.
It also provides a description (2) and an optional response converter to convert the response into a text as expected by the model.

NOTE: By default, the response converter performs a JSON serialization of the Response object.

NOTE: The `FunctionCallbackWrapper` internally resolves the function call signature based on the `MockWeatherService.Request` class.

=== Enable functions by bean name

To let the model know and call your `CurrentWeather` function you need to enable it in your prompt requests:

[source,java]
----
ChatClient chatClient = ...

ChatResponse response = chatClient.prompt("What's the weather like in San Francisco, Tokyo, and Paris?")
.functions("CurrentWeather") // Enable the function
.call().
chatResponse();

logger.info("Response: {}", response);
----

The above user question will trigger 3 calls to the `CurrentWeather` function (one for each city) and the final response will be something like this:

----
Here is the current weather for the requested cities:
- San Francisco, CA: 30.0°C
- Tokyo, Japan: 10.0°C
- Paris, France: 15.0°C
----

The link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/openai/tool/FunctionCallbackWithPlainFunctionBeanIT.java[FunctionCallbackWithPlainFunctionBeanIT.java] test demo this approach.

=== Register functions on the fly

In addition to the auto-configuration, you can register callback functions, dynamically:

[source,java]
----
ChatClient chatClient = ...

ChatResponse response = chatClient.prompt("What's the weather like in San Francisco, Tokyo, and Paris?")
.functions(new FunctionCallbackWrapper<>(
"CurrentWeather", // name
"Get the weather in location", // function description
new MockWeatherService()))
.call()
.chatResponse();
----

NOTE: The on the fly functions are enabled by default for the duration of this request.

This approach allows to choose dynamically different functions to be called based on the user input.

The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/openai/tool/FunctionCallbackInPromptIT.java[FunctionCallbackInPromptIT.java] integration test provides a complete example of how to register a function with the `ChatClient` and use it in a prompt request.

=== Tool Context

Spring AI now supports passing additional contextual information to function callbacks through a tool context. This feature allows you to provide extra data that can be used within the function execution, enhancing the flexibility and power of function calling.

The context information that is passed in as the second argument of a `java.util.BiFunction`. The `ToolContext` contains as an immutable `Map<String,Object>` allowing you to access key-value pairs.

==== How to Use Tool Context

You can set the tool context when building your chat options and use a BiFunction for your callback:

[source,java]
----
BiFunction<MockWeatherService.Request, ToolContext, MockWeatherService.Response> weatherFunction =
(request, toolContext) -> {
String sessionId = (String) toolContext.getContext().get("sessionId");
String userId = (String) toolContext.getContext().get("userId");

// Use sessionId and userId in your function logic
double temperature = 0;
if (request.location().contains("Paris")) {
temperature = 15;
}
else if (request.location().contains("Tokyo")) {
temperature = 10;
}
else if (request.location().contains("San Francisco")) {
temperature = 30;
}

return new MockWeatherService.Response(temperature, 15, 20, 2, 53, 45, MockWeatherService.Unit.C);
};


ChatResponse response = chatClient.prompt("What's the weather like in San Francisco, Tokyo, and Paris?")
.functions(FunctionCallbackWrapper.builder(weatherFunction)
.withName("getCurrentWeather")
.withDescription("Get the weather in location")
.build())
.toolContext(Map.of("sessionId", "1234", "userId", "5678"))
.call()
.chatResponse();
----

In this example, the `weatherFunction` is defined as a BiFunction that takes both the request and the tool context as parameters. This allows you to access the context directly within the function logic.

This approach allows you to pass session-specific or user-specific information to your functions, enabling more contextual and personalized responses.