讯飞星火调用
1.引入SDK
<dependency>
<groupId>io.github.briqt</groupId>
<artifactId>xunfei-spark4j</artifactId>
<version>1.2.0</version>
</dependency>
2.配置
application.yml 中 写入配置
# 讯飞星火 AI 配置
xunfei:
client:
appid: xxx
apiSecret: xxx
apiKey: xxx
新建 SparkConfig.java 读取配置信息
package com.cc.czbi.config;
import io.github.briqt.spark4j.SparkClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "xunfei.client")
@Data
public class SparkHuoConfig {
private String appid;
private String apiSecret;
private String apiKey;
@Bean
public SparkClient sparkClient() {
SparkClient sparkClient = new SparkClient();
sparkClient.apiKey = apiKey;
sparkClient.apiSecret = apiSecret;
sparkClient.appid = appid;
return sparkClient;
}
}
新建 SparkManager.java 调用星火 AI
package com.cc.czbi.manager;
import io.github.briqt.spark4j.SparkClient;
import io.github.briqt.spark4j.constant.SparkApiVersion;
import io.github.briqt.spark4j.model.SparkMessage;
import io.github.briqt.spark4j.model.SparkSyncChatResponse;
import io.github.briqt.spark4j.model.request.SparkRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Component
@Slf4j
public class SparkManager {
@Resource
private SparkClient sparkClient;
/**
* AI提示词
*/
public static final String PRECONDITION = "{这里可以给AI预设}";
/**
* 向星火AI发送请求
*
* @param content
* @return
*/
public String sendMesToAIUseSpark(final String content) {
// 消息列表,可以在此列表添加历史对话记录
List<SparkMessage> messages = new ArrayList<>();
messages.add(SparkMessage.userContent(content));
// 构造请求
SparkRequest sparkRequest = SparkRequest.builder()
// 消息列表
.messages(messages)
// 模型回答的tokens的最大长度,非必传,默认为2048
.maxTokens(2048)
// 结果随机性,取值越高随机性越强,即相同的问题得到的不同答案的可能性越高,非必传,取值为[0,1],默认为0.5
.temperature(0.2)
// 指定请求版本
.apiVersion(SparkApiVersion.V3_5)
.build();
// 同步调用
SparkSyncChatResponse chatResponse = sparkClient.chatSync(sparkRequest);
String responseContent = chatResponse.getContent();
log.info("星火AI返回的结果{}", responseContent);
return responseContent;
}
}