
<!-- Spring AI OpenAI -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>0.8.1</version> <!-- 使用最新版本 -->
</dependency>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>在application.properties / yml中配置:
# OpenAI配置
spring.ai.openai.api-key=your-api-key-here
spring.ai.openai.chat.options.model=gpt-3.5-turboimport org.springframework.ai.chat.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
publicclassAIController {
privatefinal ChatClient chatClient;
// 构造器注入
publicAIController(ChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("/ai/chat")
public String chat(@RequestParam String message) {
return chatClient.call(message);
}
}创建更结构化的提示词模板【提示词工程】,方便AI理解和推理
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@PostMapping("/ai/translate")
public String translate(@RequestBody TranslationRequest request) {
PromptTemplatepromptTemplate=newPromptTemplate("""
将以下{sourceLang}文本翻译成{targetLang}:
{text}
""");
promptTemplate.add("sourceLang", request.sourceLang());
promptTemplate.add("targetLang", request.targetLang());
promptTemplate.add("text", request.text());
return chatClient.call(promptTemplate.render());
}
// DTO:名为 TranslationRequest 的记录类(record),用于存储翻译请求的信息
// 该记录类通常用于封装翻译 API 请求所需的数据
recordTranslationRequest(String sourceLang, String targetLang, String text) {}通过命令行或开发工具启动Spring Boot项目
a.在浏览器或接口测试工具中输入URL:
http://localhost:8080/ai/chat?message=用Java写一个Hello World程序b.页面输出的内容:成功响应(HTTP 200 OK)
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}a.在接口测试工具(如Postman、ApiFox)中输入以下信息:
// json
{
"sourceLang": "中文",
"targetLang": "英文",
"text": "今天天气真好"
} b.接口返回的响应内容:成功响应(HTTP 200 ok)
// text
"Today's weather is really nice." 在application.properties / yml中添加更多参数:
# 控制生成内容
spring.ai.openai.chat.options.temperature=0.7
spring.ai.openai.chat.options.max-tokens=500全局异常捕获和处理:
import org.springframework.ai.openai.api.OpenAiApiException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(OpenAiApiException.class)
public ResponseEntity<String> handleOpenAiError(OpenAiApiException ex) {
return ResponseEntity.status(ex.getStatusCode())
.body("AI服务错误: " + ex.getMessage());
}
}src/main/java
└── com.example
└── aiapp
├── AIController.java
├── GlobalExceptionHandler.java
└── AiAppApplication.java (主类)API Key 无效时的响应:
// json
{
"status": 401,
"error": "Unauthorized",
"message": "AI服务错误: Invalid API Key"
}翻译结果会因模型版本(如 gpt-3.5-turbo 或 gpt-4)和参数(如 temperature)略有差异。
示例是典型结果,但可能返回类似 “The weather is very nice today.” 的变体。
如果需要实时逐字输出(类似 ChatGPT),交互更友好,可以改用 StreamingChatClient:
@GetMapping("/ai/chat-stream")
public Flux<String> chatStream(@RequestParam String message) {
return streamingChatClient.stream(message);
}文本过长(超过模型 token 限制)时响应会被截断;
需在 application.properties 中调整 max-tokens 参数:
spring.ai.openai.chat.options.max-tokens=2000默认返回纯文本(text/plain),若希望返回 JSON 格式,可在 Controller 中修改响应类型:
@PostMapping(value = "/ai/translate", produces = "application/json")
public Map<String, String> translate(...) {
return Map.of("result", translatedText);
} 响应示例:
// json
{ "result": "Today's weather is really nice." } 接口开发完成后,建议多使用几个请求进行测试:
1)提供其他需求:http://localhost:8080/ai/chat?message=用Python写一个斐波那契数列函数
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a)
a, b = b, a + b2)翻译不同语种:修改请求体中的sourceLang和targetLang
// json
{
"sourceLang":"英文",
"targetLang":"法语",
"text":"Hello, how are you?"
} 预期响应输出:
"Bonjour, comment allez-vous ?" 原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。