qidao123.com技术社区-IT企服评测·应用市场

标题: 《史上最简单的SpringAI+Llama3.x教程》-05-突破界限,Function Calling在 [打印本页]

作者: 风雨同行    时间: 2024-8-22 03:51
标题: 《史上最简单的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 的一般步骤:
根据上述步骤,结合你的具体应用场景,就可以实现 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一个数据。
  1. import com.fasterxml.jackson.annotation.JsonProperty;
  2. import com.fasterxml.jackson.annotation.JsonPropertyDescription;
  3. import lombok.Data;
  4. import org.springframework.context.annotation.Description;
  5. import org.springframework.stereotype.Service;
  6. import java.util.function.Function;
  7. /**
  8. * 通过@Description描述函数的用途,这样ai在多个函数中可以根据描述进行选择。
  9. */
  10. @Description("汽车价格检索")
  11. @Service
  12. public class MockSearchService implements Function<MockSearchService.SearchRequest, MockSearchService.SearchResponse> {
  13.     @Data
  14.     public static class SearchRequest {
  15.         @JsonProperty(required = true, value = "path")
  16.         @JsonPropertyDescription(value = "汽车型号")
  17.         String carType;
  18.     }
  19.     public record SearchResponse(Integer price) {
  20.     }
  21.     public SearchResponse apply(SearchRequest request) {
  22.         System.out.println(request.carType);
  23.         // mock 数据
  24.         return new SearchResponse(300000);
  25.     }
  26. }
复制代码
使用函数
注入AI模型基座,可以切换差别的AI厂商模型。本案例使用的是Ollama部署的模型。
在现实的开发中可以吸收多个函数,通过functions参数传入。然后ai会根据提问从这些函数中选择一个执行。
  1. import lombok.AllArgsConstructor;
  2. import org.springframework.ai.chat.client.ChatClient;
  3. import org.springframework.ai.chat.messages.UserMessage;
  4. import org.springframework.ai.ollama.OllamaChatModel;
  5. import org.springframework.http.MediaType;
  6. import org.springframework.http.codec.ServerSentEvent;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestParam;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import reactor.core.publisher.Flux;
  12. import static cn.hutool.json.JSONUtil.toJsonStr;
  13. /**
  14. * function calling controller
  15. *
  16. * @author JingYu
  17. * @date 2024/07/29
  18. */
  19. @RestController
  20. @RequestMapping("/function/calling")
  21. @AllArgsConstructor
  22. public class FunctionCallingController {
  23.     private final OllamaChatModel ollamaChatModel;
  24.    
  25.     /**
  26.      * 指定自定义函数回答用户的提问
  27.      *
  28.      * @param prompt       用户的提问
  29.      * @return SSE流式响应
  30.      */
  31.     @GetMapping(value = "chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  32.     public Flux<ServerSentEvent<String>> chatStreamWithFunction(@RequestParam String prompt) {
  33.         return ChatClient.create(ollamaChatModel).prompt().messages(new UserMessage(prompt))
  34.                 // spring ai会从已注册为bean的function中查找函数,
  35.                 // 将它添加到请求中。如果成功触发就会调用函数
  36.                 .functions("mockSearchService").stream()
  37.                 .chatResponse()
  38.                 .map(chatResponse -> ServerSentEvent.builder(toJsonStr(chatResponse))
  39.                         .event("message").build());
  40.     }
  41. }
复制代码
此方式是通过指定function函数的方式,在开发过程中我们是不知道应该使用哪个function的,那么我们可以通过prompt的方式让模型本身决定使用哪个函数:
  1. /**
  2. * 指定自定义函数回答用户的提问
  3. *
  4. * @param prompt       用户的提问
  5. * @return SSE流式响应
  6. */
  7. @GetMapping(value = "/prompt/chat", produces = MediaType.APPLICATION_JSON_VALUE)
  8. public ChatResponse chatStreamWithPromptFunction(@RequestParam String prompt) {
  9.     UserMessage userMessage = new UserMessage(prompt);
  10.     OllamaOptions options = OllamaOptions.builder()
  11.             .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockSearchService())
  12.                     .withName("mockSearchService")
  13.                     .withDescription("汽车价格检索")
  14.                     .withResponseConverter((response) -> "" + response.price())
  15.                     .build()))
  16.             .build();
  17.     return ollamaChatModel.call(new Prompt(List.of(userMessage), options));
  18. }
复制代码
深度分析 Function Calling 的代码布局筹划

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

下图具体说明白 Ollama API 的流程:

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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 qidao123.com技术社区-IT企服评测·应用市场 (https://dis.qidao123.com/) Powered by Discuz! X3.4