前言
随着人工智能技术的快速发展,将ai能力集成到企业级应用中变得越来越重要。spring ai作为spring生态系统中的新成员,为java开发者提供了标准化、开箱即用的ai集成方案。本教程将详细介绍如何使用spring boot集成spring ai openai starter,快速为您的应用添加智能对话功能。
一、环境准备
1. 技术要求
- jdk: 17 或更高版本
- 构建工具: maven 3.6+ 或 gradle
- spring boot: 3.2+ (推荐最新稳定版)
- openai账号: 需要在openai平台注册并获取api key
2. 创建spring boot项目
您可以通过以下两种方式之一创建项目:
方式一:使用start.spring.io
- 访问 start.spring.io
- 选择以下依赖:
- spring web
- spring ai (选择对应版本)
- 其他您可能需要的依赖(如spring security等)
方式二:手动添加依赖
如果您已有spring boot项目,直接在pom.xml中添加以下依赖:
<!-- spring ai openai starter -->
<dependency>
<groupid>io.springboot.ai</groupid>
<artifactid>spring-ai-openai-spring-boot-starter</artifactid>
<version>1.0.0</version> <!-- 请使用最新版本 -->
</dependency>
<!-- spring boot web starter (如果尚未添加) -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>二、配置openai api
1. 获取openai api key
- 登录openai平台
- 进入"api keys"页面
- 创建新的api key并妥善保存
2. 配置application.yml
在src/main/resources/application.yml文件中添加以下配置:
spring:
ai:
openai:
api-key: "sk-your-openai-api-key-here" # 替换为您的实际openai api key
base-url: "https://api.openai.com/v1" # 默认值,通常无需修改
chat:
options:
model: "gpt-4-turbo" # 您想使用的模型,如gpt-3.5-turbo, gpt-4等
temperature: 0.7 # 控制生成文本的随机性(0-2)
max-tokens: 500 # 生成的最大token数安全建议:
为了安全起见,建议不要将api key直接硬编码在配置文件中,而是使用环境变量:
spring:
ai:
openai:
api-key: ${openai_api_key} # 从环境变量读取然后,在运行应用前设置环境变量:
export openai_api_key=sk-your-openai-api-key-here
或者在windows命令提示符中:
set openai_api_key=sk-your-openai-api-key-here
三、核心功能实现
1. 基础对话功能
创建ai控制器
创建一个rest控制器来处理ai对话请求:
import org.springframework.ai.chat.chatclient;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
@restcontroller
@requestmapping("/ai")
public class aicontroller {
private final chatclient chatclient;
@autowired
public aicontroller(chatclient chatclient) {
this.chatclient = chatclient;
}
/**
* 基础对话接口
* @param message 用户输入的消息
* @return ai的回复
*/
@getmapping("/chat")
public string chat(@requestparam string message) {
return chatclient.call(message);
}
/**
* 基础对话接口(post方式)
* @param userinput 用户输入
* @return ai的回复
*/
@postmapping("/chat")
public string generatetext(@requestbody string userinput) {
return chatclient.call(userinput);
}
}测试基础对话
启动spring boot应用后,您可以通过以下方式测试:
方式一:浏览器访问
http://localhost:8080/ai/chat?message=你好,请介绍一下你自己
方式二:使用curl测试
curl -x get "http://localhost:8080/ai/chat?message=请写一个简单的java hello world程序"
方式三:使用postman等工具发送post请求
- url:
http://localhost:8080/ai/chat - method: post
- body: raw, text/plain
- 内容: "请解释spring boot的核心特性"
2. 带上下文的对话
为了让对话更有连续性,我们可以实现带上下文的对话功能:
import org.springframework.ai.chat.chatclient;
import org.springframework.ai.chat.message.message;
import org.springframework.ai.chat.message.systemmessage;
import org.springframework.ai.chat.message.usermessage;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
import java.util.arraylist;
import java.util.list;
@restcontroller
@requestmapping("/ai")
public class aicontextcontroller {
private final chatclient chatclient;
// 简单的上下文存储(生产环境应使用更可靠的存储方案)
private list<message> conversationhistory = new arraylist<>();
@autowired
public aicontextcontroller(chatclient chatclient) {
this.chatclient = chatclient;
// 初始化系统消息
conversationhistory.add(new systemmessage("你是一个专业的技术助手,擅长java开发和人工智能相关知识。"));
}
/**
* 带上下文的对话
* @param userinput 用户输入
* @return ai的回复
*/
@postmapping("/chat/context")
public string chatwithcontext(@requestbody string userinput) {
// 添加用户消息到历史记录
conversationhistory.add(new usermessage(userinput));
// 创建包含历史记录的prompt
prompt prompt = new prompt(conversationhistory);
// 调用ai服务
string response = chatclient.call(prompt).getresult().getoutput().getcontent();
// 添加ai回复到历史记录
conversationhistory.add(new usermessage(response)); // 注意:这里应该是assistantmessage,但spring ai可能没有这个类
return response;
}
/**
* 清除对话上下文
*/
@postmapping("/chat/context/clear")
public string clearcontext() {
conversationhistory.clear();
conversationhistory.add(new systemmessage("你是一个专业的技术助手,擅长java开发和人工智能相关知识。"));
return "对话上下文已清除";
}
}注意:上面的代码中使用了usermessage来表示ai的回复,这在实际情况中可能不太准确。spring ai可能提供了专门的assistantmessage类,如果没有,您可能需要自己创建或考虑使用其他方式管理上下文。
3. 高级参数控制
您可以通过自定义openaichatoptions来更精细地控制ai的行为:
import org.springframework.ai.chat.chatclient;
import org.springframework.ai.chat.prompt.prompt;
import org.springframework.ai.openai.openaichatoptions;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
@restcontroller
@requestmapping("/ai")
public class aiadvancedcontroller {
private final chatclient chatclient;
@autowired
public aiadvancedcontroller(chatclient chatclient) {
this.chatclient = chatclient;
}
/**
* 高级参数控制的对话
* @param message 用户输入
* @return ai的回复
*/
@postmapping("/chat/advanced")
public string advancedchat(@requestbody string message) {
// 自定义参数
openaichatoptions options = openaichatoptions.builder()
.withmodel("gpt-4") // 指定模型
.withtemperature(0.3) // 较低的随机性,回复更确定
.withmaxtokens(1000) // 最大生成token数
// 可以添加更多选项,如topp, frequencypenalty, presencepenalty等
.build();
// 构建 prompt
prompt request = new prompt(message, options);
return chatclient.call(request).getresult().getoutput().getcontent();
}
/**
* 使用不同模型的对话
* @param message 用户输入
* @param modelname 模型名称
* @return ai的回复
*/
@postmapping("/chat/model/{modelname}")
public string chatwithspecificmodel(@requestbody string message, @pathvariable string modelname) {
openaichatoptions options = openaichatoptions.builder()
.withmodel(modelname) // 动态指定模型
.withtemperature(0.7)
.withmaxtokens(800)
.build();
prompt request = new prompt(message, options);
return chatclient.call(request).getresult().getoutput().getcontent();
}
}4. 流式响应(server-sent events)
对于长时间运行的请求,流式响应可以提供更好的用户体验:
import org.springframework.ai.chat.streamingchatclient;
import org.springframework.ai.chat.message.usermessage;
import org.springframework.ai.chat.prompt.prompt;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.mediatype;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.flux;
@restcontroller
@requestmapping("/ai")
public class aistreamingcontroller {
private final streamingchatclient streamingchatclient;
@autowired
public aistreamingcontroller(streamingchatclient streamingchatclient) {
this.streamingchatclient = streamingchatclient;
}
/**
* 流式对话接口
* @param message 用户输入的消息
* @return 流式的ai回复
*/
@getmapping(value = "/chat/stream", produces = mediatype.text_event_stream_value)
public flux<string> streamchat(@requestparam string message) {
prompt prompt = new prompt(new usermessage(message));
return streamingchatclient.stream(prompt)
.map(content -> content.tostring());
}
/**
* 流式对话接口(post方式)
* @param message 用户输入
* @return 流式的ai回复
*/
@postmapping(value = "/chat/stream", produces = mediatype.text_event_stream_value)
public flux<string> streamchatpost(@requestbody string message) {
prompt prompt = new prompt(new usermessage(message));
return streamingchatclient.stream(prompt)
.map(content -> content.tostring());
}
}测试流式响应:
您可以使用支持sse的客户端(如postman或专门的sse客户端)来测试流式接口,或者创建一个简单的前端页面来展示流式效果。
四、进阶功能:提示词工程
提示词工程(prompt engineering)是通过精心设计提示词来引导ai生成更准确、更有用内容的技术。
1. 创建自定义提示词模板
import org.springframework.ai.chat.chatclient;
import org.springframework.ai.chat.prompt.prompttemplate;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
// 假设有一个dto类用于封装翻译请求
record translationrequest(string sourcelang, string targetlang, string text) {}
@restcontroller
@requestmapping("/ai")
public class aiprompttemplatecontroller {
private final chatclient chatclient;
@autowired
public aiprompttemplatecontroller(chatclient chatclient) {
this.chatclient = chatclient;
}
/**
* 翻译功能 - 使用提示词模板
* @param request 翻译请求
* @return 翻译结果
*/
@postmapping("/translate")
public string translate(@requestbody translationrequest request) {
// 创建提示词模板
prompttemplate prompttemplate = new prompttemplate("""
将以下{sourcelang}文本翻译成{targetlang}:
{text}
翻译结果:
""");
// 设置模板变量
prompttemplate.add("sourcelang", request.sourcelang());
prompttemplate.add("targetlang", request.targetlang());
prompttemplate.add("text", request.text());
// 渲染提示词并调用ai
return chatclient.call(prompttemplate.render()).getresult().getoutput().getcontent();
}
/**
* 代码生成 - 使用提示词模板
* @param language 编程语言
* @param description 功能描述
* @return 生成的代码
*/
@postmapping("/generate-code")
public string generatecode(@requestparam string language, @requestparam string description) {
prompttemplate prompttemplate = new prompttemplate("""
用{language}编写一个程序,实现以下功能: {description}
请提供完整的可运行代码,包括必要的导入语句和主函数。
代码应该有良好的注释和结构。
生成的代码:
""");
prompttemplate.add("language", language);
prompttemplate.add("description", description);
return chatclient.call(prompttemplate.render()).getresult().getoutput().getcontent();
}
}2. 测试提示词模板
测试翻译功能:
curl -x post -h "content-type: application/json" \
-d '{"sourcelang":"english","targetlang":"chinese","text":"hello, how are you today?"}' \
http://localhost:8080/ai/translate测试代码生成功能:
curl -x post "http://localhost:8080/ai/generate-code?language=java&description=一个简单的计算器,能够进行加减乘除运算" \ -h "content-type: application/x-www-form-urlencoded"
五、完整示例项目结构
src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── aiintegration/
│ │ ├── aiintegrationapplication.java
│ │ ├── controller/
│ │ │ ├── aicontroller.java
│ │ │ ├── aicontextcontroller.java
│ │ │ ├── aiadvancedcontroller.java
│ │ │ └── aistreamingcontroller.java
│ │ └── dto/
│ │ └── translationrequest.java
│ └── resources/
│ ├── application.yml
│ └── static/ # 可选:前端文件
└── test/
└── java/
└── com/
└── example/
└── aiintegration/
└── aiintegrationapplicationtests.java主应用类
package com.example.aiintegration;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
@springbootapplication
public class aiintegrationapplication {
public static void main(string[] args) {
springapplication.run(aiintegrationapplication.class, args);
}
}六、测试与验证
1. 启动应用
使用您的ide或命令行启动spring boot应用:
mvn spring-boot:run # 或 gradle bootrun
2. 测试接口
基础对话测试:
- get请求:
http://localhost:8080/ai/chat?message=你好,介绍一下spring boot - 或post请求到
http://localhost:8080/ai/chat,body为"你好,介绍一下spring boot"
高级参数测试:
- post请求到
http://localhost:8080/ai/chat/advanced,body为"解释微服务架构的优缺点"
流式响应测试:
- get请求:
http://localhost:8080/ai/chat/stream?message=给我讲一个笑话 - 使用支持sse的客户端查看流式效果
翻译功能测试:
curl -x post -h "content-type: application/json" \
-d '{"sourcelang":"english","targetlang":"chinese","text":"the quick brown fox jumps over the lazy dog."}' \
http://localhost:8080/ai/translate3. 单元测试
创建测试类验证chatclient的基本功能:
package com.example.aiintegration;
import org.junit.jupiter.api.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import org.springframework.ai.chat.chatclient;
import static org.junit.jupiter.api.assertions.assertnotnull;
@springboottest
class aiintegrationapplicationtests {
@autowired
private chatclient chatclient;
@test
void contextloads() {
}
@test
void testchatclient() {
string response = chatclient.call("你好,你能做什么?");
system.out.println("ai 回复: " + response);
assertnotnull(response);
}
}七、生产环境建议
1. 安全最佳实践
- api密钥管理:永远不要将api密钥硬编码在代码中,使用环境变量或密钥管理服务
- 访问控制:为ai接口添加适当的认证和授权
- 输入验证:验证所有用户输入,防止滥用和注入攻击
- 速率限制:实现api速率限制,防止滥用和超额费用
2. 性能优化
- 连接池:配置适当的网络连接池参数
- 缓存:对常见问题的ai响应实现缓存机制
- 异步处理:对复杂的ai请求考虑使用异步处理
- 监控:监控ai接口的性能和使用情况
3. 错误处理与重试
- 实现健壮的错误处理机制
- 对暂时性错误实现重试逻辑
- 监控api使用配额和限制
八、总结
通过本教程,您已经学会了如何使用spring boot集成spring ai openai starter,为您的应用添加强大的ai能力。从基础对话功能到高级的流式响应和提示词工程,spring ai提供了丰富的功能来满足各种ai集成需求。
spring ai的优势在于其标准化的api设计,使得您可以轻松切换不同的ai供应商而无需大幅修改业务代码。随着ai技术的不断发展,这种抽象层将为您的应用提供更大的灵活性和未来保障。
到此这篇关于spring boot 集成 spring ai openai starter最佳实践指南的文章就介绍到这了,更多相关spring boot spring ai openai starter内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论