
在Java生态中,构建一个“AI高级全能工程”并不意味着必须从零训练模型——更务实的做法是通过API集成最先进的大模型,用少量Java代码完成文章生成任务。下面提供两种主流方案,代码均控制在30行以内,可直接嵌入Spring Boot或普通Java项目。
使用阿里云DashScope SDK,仅需几步完成文章生成。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>2.16.7</version>
</dependency>import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import java.util.Arrays;
public class ArticleGenerator {
public static void main(String[] args) throws ApiException {
// 1. 设置API Key(建议从环境变量读取)
String apiKey = System.getenv("DASHSCOPE_API_KEY");
// 2. 构造对话消息
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("请写一篇关于人工智能未来发展趋势的短文,约300字。")
.build();
// 3. 配置生成参数
GenerationParam param = GenerationParam.builder()
.model("qwen-plus") // 可用 qwen-max 或 qwen-turbo
.messages(Arrays.asList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.temperature(0.85f)
.maxTokens(600)
.build();
// 4. 调用API并输出结果
Generation gen = new Generation();
GenerationResult result = gen.call(param, apiKey);
String article = result.getOutput().getChoices().get(0).getMessage().getContent();
System.out.println(article);
}
}运行结果示例(节选):
人工智能正从“感知”向“认知”跃迁,多模态融合、具身智能和因果推理将成为下一个十年的核心方向。与此同时,AI治理框架将逐步完善,人机协作的边界将被重新定义……
使用官方Java客户端(或简单OkHttp),代码同样精简。
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>service</artifactId>
<version>0.18.2</version>
</dependency>import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import java.util.List;
public class OpenAiArticleGenerator {
public static void main(String[] args) {
String token = System.getenv("OPENAI_API_KEY");
OpenAiService service = new OpenAiService(token);
ChatCompletionRequest request = ChatCompletionRequest.builder()
.model("gpt-3.5-turbo")
.messages(List.of(
new ChatMessage(ChatMessageRole.USER.value(),
"请用中文写一篇关于人工智能未来发展的文章,约300字。")
))
.temperature(0.85)
.maxTokens(600)
.build();
String article = service.createChatCompletion(request)
.getChoices().get(0).getMessage().getContent();
System.out.println(article);
}
}若需在生产环境中使用,建议将上述逻辑封装为Service + 配置类,并加入:
下面是一个简化的Spring Boot组件示例(仅核心代码):
@Component
public class AIGenerationService {
@Value("${ai.api-key}")
private String apiKey;
public String generateArticle(String topic, int wordCount) {
// 复用上述Generation逻辑,但将topic和maxTokens动态传入
// 并加入try-catch重试机制
return article;
}
}原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。