第一个人工智能(AI)问答Demo

发布于:2025-06-11 ⋅ 阅读:(31) ⋅ 点赞:(0)

说明:现在解决问题都用DeepSeek、ChatGPT或其他工具,AI工具的兴起、发展,现在很多其他领域的应用、系统都加入了AI功能。

本文介绍如何快速实现问答Demo,基于阿里云百炼平台。

百炼平台

登录阿里云百炼平台,创建一个API Key

在这里插入图片描述

Demo

在官方提供的API文档中,找到下面这段代码

// 建议dashscope SDK的版本 >= 2.12.0
import java.util.Arrays;
import java.lang.System;
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 com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("你是谁?")
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 此处以qwen-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }
    public static void main(String[] args) {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            // 使用日志框架记录异常信息
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}

创建一个Maven项目,引入依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dashscope-sdk-java</artifactId>
    <version>2.20.3</version>
</dependency>

依赖坐标来自Maven官网。将代码中的这里,更换成自己前面创建的API Key。

在这里插入图片描述

使用

执行,如下,返回回答,是一个JSON格式的文本数据

在这里插入图片描述

格式化后如下,其中的content是回答内容

在这里插入图片描述

这个Demo就完成了。

另外

API请求中可以加很多参数,这里介绍几个重要的

  • 在这里插入图片描述

总结

本文介绍如何快速实现一个问答Demo


网站公告

今日签到

点亮在社区的每一天
去签到