好的,继续我们的 SpringAI 之旅!让我们从代码开始,一步步揭开 SpringAI 的神秘面纱。
环境准备,“开工”的第一步
在开始之前,我们需要确保开发环境已经准备就绪。首先,确保你已经安装了 JDK 17,并且使用的是 Spring Boot 3.x 版本。这是 SpringAI 的 “根基”,没有它,我们的 AI 应用就无法“生长”。
接下来,在你的 pom.xml 文件中添加 OpenAI 启动器依赖,这样我们就可以开始使用 SpringAI 提供的功能了。

<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>

配置 API 密钥,开启 AI 的 “密室”
在 application.yml 文件中配置 OpenAI 的 API 密钥。这是与 OpenAI 模型进行通信的 “通行证”,没有它,我们无法调用任何模型。


spring:
  ai:
    openai:
      api-key: YOUR_API_KEY
      chat:
        options:
          model: gpt-3.5-turbo
          temperature: 0.7

编写代码,“魔法” 的开始
现在,我们开始编写代码,让 SpringAI 的功能在项目中 “施展”。
定义函数逻辑,给 AI 装上 “大脑”
以天气查询功能为例,我们定义一个 WeatherService,它将作为 AI 调用的 “大脑”,处理用户的请求并返回结果。

@Service
public class WeatherService {

    private Map<String, String> weatherData = Map.of(
        "北京", "晴,气温25°C",
        "上海", "多云,气温28°C",
        "广州", "阵雨,气温30°C"
    );

    @Function(
        name = "getCurrentWeather",
        description = "获取指定城市的当前天气信息",
        inputType = @Function.Parameter(
            type = "object",
            properties = @Function.ParameterProperty(
                name = "location",
                type = "string",
                description = "城市名称,如 '北京'"
            )
        )
    )
    public String getWeather(@RequestParam String location) {
        return weatherData.getOrDefault(location, "暂无该城市天气数据");
    }
}

注册函数到 SpringAI,打通 AI 的 “任督二脉”
为了让 AI 能够调用这个函数,我们需要将其注册到 SpringAI 中。这就像为 AI 打通“任督二脉”,让它能够感知和使用我们的函数。

@Configuration
public class FunctionConfig {

    @Bean
    public FunctionCallback weatherFunction(WeatherService weatherService) {
        return new FunctionCallbackWrapper<>(
            "getCurrentWeather",
            "获取天气信息",
            weatherService::getWeather,
            new WeatherRequestConverter()
        );
    }

    private static class WeatherRequestConverter implements Converter<String, String> {

        @Override
        public String convert(String source) {
            return source.replaceAll("\"", "").split(":")[1].trim();
        }
    }
}

启用函数调用,让 AI “动” 起来
最后,我们需要启用函数调用,让 AI 真正“动”起来。

@Configuration
public class ChatConfig {

    @Bean
    public ChatClient chatClient(
        OpenAiChatClient chatClient,
        List<FunctionCallback> functionCallbacks
    ) {
        chatClient.setFunctionCallbacks(functionCallbacks);
        return chatClient;
    }
}

API 调用,“成果” 的检验
现在,我们已经完成了 SpringAI 的集成,接下来就是见证成果的时候了。让我们通过 API 调用来测试我们的功能。
构建控制器,开启 AI 的 “对话”

@RestController
public class ChatController {

    @Autowired
    private OpenAiChatClient chatClient;

    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
        return chatClient.call(message);
    }

    @GetMapping("/chat/stream")
    public Flux<String> streamChat(@RequestParam String message) {
        return chatClient.stream(new Prompt(message, OpenAiChatOptions.builder()
                .withModel("gpt-4")
                .withTemperature(0.4F)
                .build()))
            .map(response -> response.getResult().getOutput().getContent());
    }
}

运行与测试,“魔法” 的验证
启动应用后,访问 /chat?message=你好 即可获取模型响应。流式接口 /chat/stream 适用于长文本逐句返回的场景。当然我们实际企业级开发中使用SpringAI是不大够的,目前我们在用JBoltAI SpringBoot版,大模型对接类工作都封装好了,直接可以用,已经集成了知识库、思维链等一系列高级应用。

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐