Spring AI 最快 API 开发指南!
Spring AI 快速开发,本文以 码本AI 为例
# Spring AI 最快 API 开发指南!
*Spring 技术栈*
Spring AI 快速开发,本文以 码本AI 为例
## 目录
[TOC]
## 创建项目

添加两个模板依赖即可

## 在 启动类中创建一个 bean
```java
package org.example.springai;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringAiApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAiApplication.class, args);
}
@Bean
public ChatClient chatClient(ChatClient.Builder builder) {
return builder.build();
}
}
```
## 在控制器中创建一个 web API
```java
package org.example.springai.controller;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.ArrayList;
import java.util.Map;
@RestController
@RequestMapping("/ai")
public class ChatController {
private final ChatClient chatClient;
@Autowired
public ChatController(ChatClient aiClient) {
this.chatClient = aiClient;
}
@GetMapping("/chat")
public Map<String, String> completion(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
return Map.of(
"chat",
chatClient.prompt(message)
.messages(new ArrayList<>())
.call()
.chatResponse()
.getResult()
.getOutput()
.getText());
}
}
```
## 修改 yaml 配置 对接模型服务
```yaml
spring:
ai:
openai:
api-key: "id:sk" # 替换为你的 码本服务id:码本sk 冒号不要删除 可以在 https://www.lingyuzhao.top/b/Article/377388518747589 获取到!
base-url: "https://api.get.lingyuzhao.top:8081/api/chat/none/"
chat:
options:
model: "model02" # 指定使用的模型
```
------
***操作记录***
作者:[zhao](https://www.lingyuzhao.top//index.html?search=4 "zhao")
操作时间:2025-04-28 16:29:32 星期一 【时区:UTC 8】
事件描述备注:保存/发布
中国 天津市 天津
[](如果不需要此记录可以手动删除,每次保存都会自动的追加记录)