当前位置:   article > 正文

《史上最简单的SpringAI+Llama3.x教程》-05-打破界限,Function Calling在业务场景中的应用_spring ai ollama function

spring ai ollama function

什么是Function Calling

Function Calling 是一种技术,它允许大型语言模型(如GPT)在生成文本的过程中调用外部函数或服务。

这种功能的核心在于,模型本身不直接执行函数,而是生成包含函数名称和执行函数所需参数的JSON,然后由外部系统执行这些函数,并将结果返回给模型以完成对话或生成任务。

Function Calling 主要解决了大型语言模型在处理任务时的局限性,尤其是模型自身无法获取实时信息或执行复杂计算的问题。

通过Function Calling,模型可以利用外部工具或服务来扩展其能力,从而能够处理更广泛的任务,如实时数据查询、复杂计算等。

Spring AI 如何实现 Function Calling

Spring AI 提供了一种机制,允许开发者向大型语言模型(LLM)注册自定义函数,并使模型能够在适当的时候调用这些函数。这种功能称为 Function Calling,它可以增强模型的能力,使其能够访问外部工具或动态执行任务。

以下是实现 Function Calling 的一般步骤:

  1. 定义函数接口:首先,你需要定义一个遵循 java.util.function.Function 接口的类,该类定义了函数的签名,即函数的输入和输出类型。
  2. 注册函数为 Spring Bean:通过在 Spring 配置类中声明一个 @Bean 方法,将你的函数实现作为 Spring Bean 注册。你可以使用 @Description 注解来提供函数的描述,这有助于模型理解何时调用该函数。
  3. 创建 FunctionCallbackWrapper:Spring AI 提供了 FunctionCallbackWrapper 类,它封装了函数的调用逻辑,并将其注册为 FunctionCallback。这是因为 LLM 模型本身并不直接调用函数,而是生成一个包含函数调用详细信息的 JSON 对象,由客户端处理并执行函数。
  4. 配置 ChatOptions:在创建 OpenAiChatClient 或其他支持 Function Calling 的聊天客户端时,你需要配置 ChatOptions,并通过 withFunction 方法启用你注册的函数。
  5. 调用函数:在与模型的交互过程中,当模型决定需要调用一个函数时,它会生成一个 JSON 对象,客户端收到这个对象后,会调用注册的函数,并将结果返回给模型。
  6. 处理函数调用结果:函数执行后,你需要处理返回的结果,并根据需要将结果转换为模型可以理解的格式。

根据上述步骤,结合你的具体应用场景,就可以实现 Spring AI 中的 Function Calling 功能。

一个Function Calling 的Demo

目前SpringAI已经支持了多个模型的function Calling能力,如下:

在这里插入图片描述

Ollama API并不直接调用这些函数;相反,模型会生成JSON,在代码中使用这个JSON来调用函数,并将结果返回给模型以继续对话。

Spring AI使得这一过程变得简单,就像定义一个返回java.util.Function@Bean一样,并在调用时提供bean名称作为选项。

在底层,Spring使用适当的适配器代码来包装您的POJO(简单的Java对象,即函数),这个代码支持与AI模型的交互,从而避免了编写繁琐的样板代码。

底层基础设施的核心是FunctionCallback.java接口和配套的FunctionCallbackWrapper.java实用程序类,它们用于简化Java回调函数的实现和注册。

上手试试

咱们本地使用的是Llama3.1模型来实现Function Calling能力,你可以想象有这样一个场景:

咱们之前聊过一个汽车销售问答平台,现在我希望通过Google搜索的能力,获取市面上某款车的价格,然后上浮2%报价给消费者。

定义一个Function方法

此处为了实现效果,咱们只是mock一个数据。

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import lombok.Data;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Service;

import java.util.function.Function;
/**
 * 通过@Description描述函数的用途,这样ai在多个函数中可以根据描述进行选择。
 */
@Description("汽车价格检索")
@Service
public class MockSearchService implements Function<MockSearchService.SearchRequest, MockSearchService.SearchResponse> {

    @Data
    public static class SearchRequest {
        @JsonProperty(required = true, value = "path")
        @JsonPropertyDescription(value = "汽车型号")
        String carType;
    }

    public record SearchResponse(Integer price) {
    }

    public SearchResponse apply(SearchRequest request) {
        System.out.println(request.carType);
        // mock 数据
        return new SearchResponse(300000);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

使用函数

注入AI模型基座,可以切换不同的AI厂商模型。本案例使用的是Ollama部署的模型。

在实际的开发中可以接收多个函数,通过functions参数传入。然后ai会根据提问从这些函数中选择一个执行。

import lombok.AllArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static cn.hutool.json.JSONUtil.toJsonStr;

/**
 * function calling controller
 *
 * @author JingYu
 * @date 2024/07/29
 */
@RestController
@RequestMapping("/function/calling")
@AllArgsConstructor
public class FunctionCallingController {


    private final OllamaChatModel ollamaChatModel;
    
    /**
     * 指定自定义函数回答用户的提问
     *
     * @param prompt       用户的提问
     * @return SSE流式响应
     */
    @GetMapping(value = "chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> chatStreamWithFunction(@RequestParam String prompt) {
        return ChatClient.create(ollamaChatModel).prompt().messages(new UserMessage(prompt))
                // spring ai会从已注册为bean的function中查找函数,
                // 将它添加到请求中。如果成功触发就会调用函数
                .functions("mockSearchService").stream()
                .chatResponse()
                .map(chatResponse -> ServerSentEvent.builder(toJsonStr(chatResponse))
                        .event("message").build());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

此方式是通过指定function函数的方式,在开发过程中我们是不知道应该使用哪个function的,那么我们可以通过prompt的方式让模型自己决定使用哪个函数:

/**
 * 指定自定义函数回答用户的提问
 *
 * @param prompt       用户的提问
 * @return SSE流式响应
 */
@GetMapping(value = "/prompt/chat", produces = MediaType.APPLICATION_JSON_VALUE)
public ChatResponse chatStreamWithPromptFunction(@RequestParam String prompt) {


    UserMessage userMessage = new UserMessage(prompt);

    OllamaOptions options = OllamaOptions.builder()
            .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockSearchService())
                    .withName("mockSearchService")
                    .withDescription("汽车价格检索")
                    .withResponseConverter((response) -> "" + response.price())
                    .build()))
            .build();

    return ollamaChatModel.call(new Prompt(List.of(userMessage), options));

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

深度分析 Function Calling 的代码结构设计

下图说明了 OllamaChatModel 函数调用的流程:

在这里插入图片描述

下图详细说明了 Ollama API 的流程:

在这里插入图片描述

Ollama API 调用官方案例:spring-ai/models/spring-ai-ollama/src/test/java/org/springframework/ai/ollama/api/tool/OllamaApiTool

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/974441
推荐阅读
相关标签
  

闽ICP备14008679号