在Trae?IDE中創(chuàng)建Spring?AI項(xiàng)目的實(shí)現(xiàn)步驟
Trae是 ByteDance 推出的 AI 驅(qū)動(dòng)的集成開(kāi)發(fā)環(huán)境(IDE)。Trae 是一個(gè)下一代 AI 代碼編輯器,具有智能代碼生成、自然語(yǔ)言交互、圖像輔助需求表達(dá)等功能。

- 在 Trae IDE 中創(chuàng)建 Spring AI 項(xiàng)目
- 使用 Spring AI 框架創(chuàng)建一個(gè) AI 應(yīng)用項(xiàng)目
創(chuàng)建一個(gè)使用 Spring AI 框架創(chuàng)建簡(jiǎn)單 AI 應(yīng)用的完整示例:
Spring AI 項(xiàng)目完整示例
1. 項(xiàng)目結(jié)構(gòu)
spring-ai-demo/ ├── src/main/java/com/example/springai/ │ ├── SpringAiDemoApplication.java │ ├── controller/ │ │ └── ChatController.java │ ├── service/ │ │ └── ChatService.java │ └── config/ │ └── AiConfig.java ├── src/main/resources/ │ └── application.yml └── pom.xml
2. pom.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-ai-demo</artifactId>
<version>1.0.0</version>
<name>Spring AI Demo</name>
<properties>
<java.version>17</java.version>
<spring-ai.version>0.8.1</spring-ai.version>
</properties>
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring AI OpenAI -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>${spring-ai.version}</version>
</dependency>
<!-- Spring AI Ollama (本地 AI 模型支持) -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
<version>${spring-ai.version}</version>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3. 應(yīng)用配置 (application.yml)
spring:
application:
name: spring-ai-demo
ai:
openai:
api-key: ${OPENAI_API_KEY:your-openai-api-key-here}
chat:
options:
model: gpt-3.5-turbo
temperature: 0.7
max-tokens: 1000
ollama:
base-url: http://localhost:11434
chat:
options:
model: llama2
temperature: 0.7
server:
port: 8080
logging:
level:
org.springframework.ai: DEBUG
4. 主應(yīng)用類
package com.example.springai;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringAiDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAiDemoApplication.class, args);
}
}
5. AI 配置類
package com.example.springai.config;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class AiConfig {
@Value("${spring.ai.openai.api-key}")
private String openAiApiKey;
@Bean
@Primary
public ChatClient openAiChatClient() {
var openAiApi = new OpenAiApi(openAiApiKey);
return new OpenAiChatClient(openAiApi);
}
@Bean
public PromptTemplate systemPromptTemplate() {
return new PromptTemplate("""
你是一個(gè)友善的AI助手。請(qǐng)用中文回答問(wèn)題,并保持回答的準(zhǔn)確性和有幫助性。
如果你不確定答案,請(qǐng)誠(chéng)實(shí)地說(shuō)明。
""");
}
}
6. 服務(wù)層
package com.example.springai.service;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Map;
@Service
public class ChatService {
private final ChatClient chatClient;
private final PromptTemplate systemPromptTemplate;
@Autowired
public ChatService(ChatClient chatClient, PromptTemplate systemPromptTemplate) {
this.chatClient = chatClient;
this.systemPromptTemplate = systemPromptTemplate;
}
/**
* 簡(jiǎn)單聊天
*/
public String simpleChat(String userMessage) {
UserMessage message = new UserMessage(userMessage);
ChatResponse response = chatClient.call(new Prompt(List.of(message)));
return response.getResult().getOutput().getContent();
}
/**
* 帶系統(tǒng)提示的聊天
*/
public String chatWithSystem(String userMessage) {
SystemMessage systemMessage = new SystemMessage(systemPromptTemplate.render());
UserMessage userMsg = new UserMessage(userMessage);
List<Message> messages = List.of(systemMessage, userMsg);
ChatResponse response = chatClient.call(new Prompt(messages));
return response.getResult().getOutput().getContent();
}
/**
* 模板化聊天
*/
public String templateChat(String topic, String style) {
PromptTemplate promptTemplate = new PromptTemplate("""
請(qǐng)以{style}的風(fēng)格,詳細(xì)介紹{topic}。
要求:
1. 內(nèi)容準(zhǔn)確專業(yè)
2. 結(jié)構(gòu)清晰
3. 適合初學(xué)者理解
""");
Map<String, Object> model = Map.of(
"topic", topic,
"style", style
);
Prompt prompt = promptTemplate.create(model);
ChatResponse response = chatClient.call(prompt);
return response.getResult().getOutput().getContent();
}
/**
* 代碼生成助手
*/
public String generateCode(String language, String description) {
PromptTemplate codeTemplate = new PromptTemplate("""
請(qǐng)用{language}編程語(yǔ)言生成代碼,實(shí)現(xiàn)以下功能:
{description}
要求:
1. 代碼要有詳細(xì)注釋
2. 遵循最佳實(shí)踐
3. 包含錯(cuò)誤處理
4. 提供使用示例
""");
Map<String, Object> model = Map.of(
"language", language,
"description", description
);
Prompt prompt = codeTemplate.create(model);
ChatResponse response = chatClient.call(prompt);
return response.getResult().getOutput().getContent();
}
}
7. 控制器層
package com.example.springai.controller;
import com.example.springai.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*")
public class ChatController {
private final ChatService chatService;
@Autowired
public ChatController(ChatService chatService) {
this.chatService = chatService;
}
/**
* 簡(jiǎn)單聊天接口
*/
@PostMapping("/simple")
public ResponseEntity<Map<String, String>> simpleChat(@RequestBody Map<String, String> request) {
try {
String userMessage = request.get("message");
if (userMessage == null || userMessage.trim().isEmpty()) {
return ResponseEntity.badRequest()
.body(Map.of("error", "消息內(nèi)容不能為空"));
}
String response = chatService.simpleChat(userMessage);
return ResponseEntity.ok(Map.of(
"message", userMessage,
"response", response
));
} catch (Exception e) {
return ResponseEntity.internalServerError()
.body(Map.of("error", "處理請(qǐng)求時(shí)發(fā)生錯(cuò)誤: " + e.getMessage()));
}
}
/**
* 系統(tǒng)提示聊天接口
*/
@PostMapping("/system")
public ResponseEntity<Map<String, String>> systemChat(@RequestBody Map<String, String> request) {
try {
String userMessage = request.get("message");
String response = chatService.chatWithSystem(userMessage);
return ResponseEntity.ok(Map.of(
"message", userMessage,
"response", response
));
} catch (Exception e) {
return ResponseEntity.internalServerError()
.body(Map.of("error", "處理請(qǐng)求時(shí)發(fā)生錯(cuò)誤: " + e.getMessage()));
}
}
/**
* 模板聊天接口
*/
@PostMapping("/template")
public ResponseEntity<Map<String, String>> templateChat(@RequestBody Map<String, String> request) {
try {
String topic = request.get("topic");
String style = request.get("style");
if (topic == null || style == null) {
return ResponseEntity.badRequest()
.body(Map.of("error", "topic 和 style 參數(shù)不能為空"));
}
String response = chatService.templateChat(topic, style);
return ResponseEntity.ok(Map.of(
"topic", topic,
"style", style,
"response", response
));
} catch (Exception e) {
return ResponseEntity.internalServerError()
.body(Map.of("error", "處理請(qǐng)求時(shí)發(fā)生錯(cuò)誤: " + e.getMessage()));
}
}
/**
* 代碼生成接口
*/
@PostMapping("/code")
public ResponseEntity<Map<String, String>> generateCode(@RequestBody Map<String, String> request) {
try {
String language = request.get("language");
String description = request.get("description");
if (language == null || description == null) {
return ResponseEntity.badRequest()
.body(Map.of("error", "language 和 description 參數(shù)不能為空"));
}
String response = chatService.generateCode(language, description);
return ResponseEntity.ok(Map.of(
"language", language,
"description", description,
"code", response
));
} catch (Exception e) {
return ResponseEntity.internalServerError()
.body(Map.of("error", "處理請(qǐng)求時(shí)發(fā)生錯(cuò)誤: " + e.getMessage()));
}
}
/**
* 健康檢查
*/
@GetMapping("/health")
public ResponseEntity<Map<String, String>> health() {
return ResponseEntity.ok(Map.of(
"status", "ok",
"message", "Spring AI 服務(wù)運(yùn)行正常"
));
}
}
8. 使用示例
啟動(dòng)應(yīng)用后,您可以通過(guò)以下方式測(cè)試:
簡(jiǎn)單聊天
curl -X POST http://localhost:8080/api/chat/simple \
-H "Content-Type: application/json" \
-d '{"message": "你好,請(qǐng)介紹一下Spring框架"}'
模板聊天
curl -X POST http://localhost:8080/api/chat/template \
-H "Content-Type: application/json" \
-d '{"topic": "Spring Boot", "style": "通俗易懂"}'
代碼生成
curl -X POST http://localhost:8080/api/chat/code \
-H "Content-Type: application/json" \
-d '{"language": "Java", "description": "實(shí)現(xiàn)一個(gè)簡(jiǎn)單的用戶注冊(cè)功能"}'
9. 環(huán)境配置說(shuō)明
- OpenAI 配置:需要設(shè)置環(huán)境變量
OPENAI_API_KEY - 本地 Ollama 配置:需要先安裝并運(yùn)行 Ollama 服務(wù)
到此這篇關(guān)于在Trae IDE中創(chuàng)建Spring AI項(xiàng)目的實(shí)現(xiàn)步驟的文章就介紹到這了,更多相關(guān)Trae IDE創(chuàng)建Spring AI項(xiàng)目?jī)?nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java GUI圖形界面開(kāi)發(fā)實(shí)現(xiàn)小型計(jì)算器流程詳解
本文章向大家介紹Java GUI圖形界面開(kāi)發(fā)實(shí)現(xiàn)小型計(jì)算器,主要包括布局管理器使用實(shí)例、應(yīng)用技巧、基本知識(shí)點(diǎn)總結(jié)和需要注意事項(xiàng),具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08
基于EasyExcel實(shí)現(xiàn)百萬(wàn)級(jí)數(shù)據(jù)導(dǎo)入導(dǎo)出詳解
大數(shù)據(jù)的導(dǎo)入和導(dǎo)出,相信大家在日常的開(kāi)發(fā)、面試中都會(huì)遇到。本文將為大家詳細(xì)介紹一下如何利用EasyExcel實(shí)現(xiàn)百萬(wàn)級(jí)數(shù)據(jù)導(dǎo)入導(dǎo)出,需要的可以參考一下2023-01-01
JAVA實(shí)現(xiàn)Token自動(dòng)續(xù)期機(jī)制的示例代碼
本文主要介紹了JAVA實(shí)現(xiàn)Token自動(dòng)續(xù)期機(jī)制的示例代碼,通過(guò)動(dòng)態(tài)調(diào)整會(huì)話生命周期平衡安全性與用戶體驗(yàn),解決固定有效期Token帶來(lái)的風(fēng)險(xiǎn)與不便,感興趣的可以了解一下2025-09-09
Java實(shí)現(xiàn)XML格式與JSON格式互相轉(zhuǎn)換的方法
這篇文章主要介紹了Java實(shí)現(xiàn)XML格式與JSON格式互相轉(zhuǎn)換的方法,方法通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),選擇使用哪種格式通常取決于項(xiàng)目的需求和上下文,所以格式轉(zhuǎn)換就成了我們必備的技能,具體實(shí)現(xiàn)代碼跟隨小編一起看看吧2023-10-10
SchedulingConfigurer實(shí)現(xiàn)動(dòng)態(tài)定時(shí),導(dǎo)致ApplicationRunner無(wú)效解決
這篇文章主要介紹了SchedulingConfigurer實(shí)現(xiàn)動(dòng)態(tài)定時(shí),導(dǎo)致ApplicationRunner無(wú)效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
Spring Boot 整合單機(jī)websocket的步驟 附github源碼
websocket 是一個(gè)通信協(xié)議,通過(guò)單個(gè) TCP 連接提供全雙工通信,這篇文章主要介紹了Spring Boot 整合單機(jī)websocket的步驟(附github源碼),需要的朋友可以參考下2021-10-10

