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

什么是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);
    }
}

使用函数

注入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());
    }
}

此方式是通过指定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));

}

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

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

在这里插入图片描述

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

在这里插入图片描述

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

  • 35
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
根据提供的引用信息,你遇到的问题是在编译过程出现了错误。具体来说,错误信息是"\k_quants.h(145): error C2059: 语法错误:“)”"。根据提供的引用,这个错误可能是在编译GPU版本的llama.cpp文件时出现的,并且与选项'gpu-architecture'的值为'native'有关。 解决这个问题的步骤如下: 1. 首先,查看编译错误的具体位置,即\k_quants.h文件的第145行。 2. 在该行附近检查代码,查找是否有语法错误,例如缺少分号或括号不匹配等。 3. 如果代码没有明显的语法错误,可以考虑检查编译选项和环境设置是否正确。特别是关于选项'gpu-architecture'的值,确保它被正确定义和使用。 4. 如果是Makefile文件导致的问题,则需要修改Makefile源码,确保编译选项被正确设置。 5. 重新编译代码并进行测试,确保问题已经解决。 请注意,以上步骤仅供参考,具体解决方法可能因个人环境和代码情况而异。建议仔细检查错误信息和相关代码,结合实际情况采取相应的解决措施。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [【AI实战】llama.cpp量化cuBLAS编译;nvcc fatal:Value ‘native‘ is not defined for option ‘gpu-...](https://blog.csdn.net/zengNLP/article/details/131576986)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [ubuntu下编译时遇到的错误及解决方式](https://blog.csdn.net/weixin_30267691/article/details/94986381)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

静愚 AGI

你的善意终将流回自己,加油!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值