项目中使用AI功能
方式一:直接调用OpenAi或者其他Ai原始模型官网的接口(以OpenAl为例)
-
OpenAl官方文档:https://platform.openai.com/docs/api-reference
-
直接调用OpenAi优缺点:
- 优点:不经封装,最灵活,最原始
- 缺点:需要付费
-
本质上OpenAl就是提供了HTTP接口,我们可以用任何语言去调用
-
在请求头中指定OPENAI API KEY
Authorization:Bearer OPENAI API KEY
-
找到你要使用的接☐,比如Al对话接口:https://platform.openai.com/docs/api-reference/chat/create
-
按照接口文档的示例,构造HTTP请求,比如用Hutool工具类、或者HTTPClient
-
-
实例代码:
/**
* AI 对话(需要自己创建请求响应对象)
*
* @param request
* @param openAiApiKey
* @return
*/
public CreateChatCompletionResponse createChatCompletion(CreateChatCompletionRequest request, String openAiApiKey) {
if (StringUtils.isBlank(openAiApiKey)) {
throw new BusinessException(ErrorCode.PARAMS_ERROR, "未传 openAiApiKey");
}
String url = "https://api.openai.com/v1/chat/completions";
String json = JSONUtil.toJsonStr(request);
String result = HttpRequest.post(url)
.header("Authorization", "Bearer " + openAiApiKey)
.body(json)
.execute()
.body();
return JSONUtil.toBean(result, CreateChatCompletionResponse.class);
}
方式二:使用云服务商提供的封装接口(比如:Azure云)
- 优缺点:
- 优点:本地都用
- 缺点:依然要钱,而且可能比直接调用原始的接口更贵
方式三:鱼聪明AI开放平台
-
鱼聪明 AI 提供了现成的SDK来让大家更方便地使用AI能力
-
参考文章操作:https://github.com/liyupi/yucongming-java-sdk
-
鱼聪明 Al 网站:https://yucongming.com/ (也可以直接公众号搜索【鱼聪明Al】移动端使用)
-
优缺点:
-
优点:目前不要钱,而且有很多现成的模型(prompt系统预设)给大家用
-
缺点:不灵活,但是可以定义自己的模型
-
-
实例代码:
AiManager
类
/**
* @author Shier
* CreateTime 2023/5/21 10:42
*/
@Service
public class AiManager {
@Resource
private YuCongMingClient congMingClient;
public String doChat(String message) {
DevChatRequest devChatRequest = new DevChatRequest();
// 鱼聪明平台模型ID
devChatRequest.setModelId(1660118603963301890L);
devChatRequest.setMessage(message);
BaseResponse<DevChatResponse> response = congMingClient.doChat(devChatRequest);
if (response == null) {
throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 响应错误");
}
return response.getData().getContent();
}
}
测试类:
/**
* @author Shier
* CreateTime 2023/5/21 10:48
*/
@SpringBootTest
class AiManagerTest {
@Resource
private AiManager aiManager;
@Test
void doChat() {
String doChat = aiManager.doChat("湖南长沙");
System.out.println(doChat);
}
}