Spring AI Java程序员的AI之Spring AI(二)

Spring AI之函数调用实战与原理分析

  • 历史Spring AI文章
  • 一丶Spring AI 函数调用
    • 定义工具函数Function
    • 工具函数调用
    • FunctionCallback工具函数
  • 二丶 Spring AI 函数调用源码解析
    • 请求处理
    • 请求调用
    • 函数调用
    • 交互流程图
  • 三丶 案例
  • 总结

历史Spring AI文章

Spring AI Java程序员的AI之Spring AI(一)

一丶Spring AI 函数调用

定义工具函数Function

在Spring AI中,如果一个Bean实现了Function接口,那么它就是一个工具函数,并且通过@Description注解可以描述该工具的作用是什么,如果工具有需要接收参数,也可以通过@Schema注解来对参数进行定义,比如以下工具是用来获取指定地点的当前时间的,并且address参数用来接收具体的地点:

package com.qjc.demo.service;

import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.function.Function;

/***
 * @projectName spring-ai-demo
 * @packageName com.qjc.demo.service
 * @author qjc
 * @description TODO
 * @Email [email protected]
 * @date 2024-10-16 09:50
 **/
@Component
@Description("获取指定地点的当前时间")
public class DateService implements Function<DateService.Request, DateService.Response> {
   

    public record Request(@Schema(description = "地点") String address) {
    }

    public record Response(String date) {
    }

    @Override
    public Response apply(Request request) {
   
        System.out.println(request.address);
        return new Response(String.format("%s的当前时间是%s", request.address, LocalDateTime.now()));
    }
}

工具函数调用

当向大模型提问时,需要指定所要调用的工具函数,利用OpenAiChatOptions指定对应的beanName就可以了,比如:

@GetMapping("/function")
public String function(@RequestParam String message) {
   
    Prompt prompt = new Prompt(message, OpenAiChatOptions.builder().withFunction("dateService").build());
    Generation generation = chatClient.call(prompt).getResult();
    return (generation != null) ? generation.getOutput().getContent() : "";
}

FunctionCallback工具函数

还可以直接在提问时直接定义并调用工具,比如:

@GetMapping("/functionCallback")
public String functionCallback(@RequestParam String message) {
   
    Prompt prompt = new Prompt(message, OpenAiChatOptions.builder().withFunctionCallbacks(
        List.of(FunctionCallbackWrapper.builder(new DateService())
                .withName("dateService")
                .withDescription("获取指定地点的当前时间").build())
    ).build());
    Generation generation = chatClient.call(prompt).getResult();
    return (generation != null) ? generation.getOutput().getContent() : "";
}

通过这种方式,就不需要将DateService定义为Bean了,当然这样定义的工具只能functionCallback接口单独使用了,而定义Bean则可以让多个接口共享使用。

不过有时候,大模型给你的答案或工具参数可能是英文的

那么可以使用SystemMessage来设置系统提示词,比如:

@GetMapping("/functionCallback")
public String functionCallback(@RequestParam 

你可能感兴趣的:(java,java,人工智能,spring,spring,boot,Spring,AI,chatgpt)