调用讯飞星辰平台的免费千问大模型接口

先到官网申请模型:

image

需要先创建应用:

image

创建应用https://console.xfyun.cn/app/myapp

image

在模型服务列表中找到刚创建的服务,找到api调用接口和文档,根据文档进行:https://maas.xfyun.cn/modelService

image

进入接口文档进行配置:

image

我选用的HTTP协议,进入文档页显示该接口可以正式使用。如您需要申请使用,请点击前往产品页面 领取免费额度。
意思是要去申请额度才能使用,找免费的下订单:
image
image
 
imageimage
请求调用代码:
private static final String API_KEY = "xxx:xxx";
private static final String API_URL = "https://maas-api.cn-huabei-1.xf-yun.com/v2";
private static final String MODEL_ID = "xxx";
public String chat(String userMessage) {
        RestTemplate restTemplate = new RestTemplate(); // 请求模板,用于http请求格式转换
        // 构建http请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(config.getApiKey()); // Authorization: Bearer <apiKey>

        // 构建 OpenAI 格式的请求体 model+role+content+message+temperature+max_tokens+lora_id+include_usage+stream_options
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", config.getModelId());
        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", userMessage);
        messages.add(userMsg);
        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 5000);
        Map<String, String> extra_header_map = new HashMap<>();
        extra_header_map.put("lora_id", "0");
        requestBody.put("extra_headers", userMsg);
        Map<String, Boolean> include_usage_map = new HashMap<>();
        include_usage_map.put("include_usage", true);
        requestBody.put("stream_options", extra_header_map);

        // 构建HTTP请求并发送请求获取响应结果
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.exchange(config.getApiUrl(), HttpMethod.POST, entity, String.class);
        // 从 response 中提取内容(路径:choices[0].message.content)
        ObjectMapper mapper = new ObjectMapper();
        Map<?, ?> body;
        try {
            body = mapper.readValue(response.getBody(), Map.class);
            System.out.println(body);
            body = mapper.readValue(response.getBody(), Map.class);
            System.out.println(body);
            if (body.isEmpty() || !body.containsKey("choices") || !(body.get("choices") instanceof List<?>)) {
                
                throw new BusinessException(ErrorCode.CHAT_RETURN_ERROR);

            }
            List<?> choices = (List<?>) body.get("choices");
                
            if (!choices.isEmpty() && choices.get(0) instanceof Map<?, ?>) {
                Map<?, ?> choice0 = (Map<?, ?>) choices.get(0);
                if (!choice0.containsKey("message") || !(choice0.get("message") instanceof Map<?, ?>)) {
                    throw new BusinessException(ErrorCode.CHAT_RETURN_ERROR);
                }
                Map<?, ?> message = (Map<?, ?>) choice0.get("message");
                // Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                return (String) message.get("content");
            } else {
                throw new BusinessException(ErrorCode.CHAT_RETURN_ERROR);
            }
        } catch (JsonProcessingException e) {
            log.info("Json转换失败" + e.getMessage());;
            throw new BusinessException(ErrorCode.CHAT_RETURN_ERROR);
        }
    }

写测试类:

@Slf4j
@SpringBootTest(classes = MyApplication.class) // 一定要指定main class
public class XingHuoTest {
    @Autowired
    private ChartServiceImpl chartServiceImpl;

    @Test
    public void testQwen3codernext() {
        // 消息列表,可以在此列表添加历史对话记录
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("请你扮演我的语文老师李老师,问我讲解问题问题,希望你可以保证知识准确,逻辑严谨。");
        stringBuffer.append("鲁迅和周树人小时候打过架吗?");
        String re = chartServiceImpl.chat(stringBuffer.substring(0));
        
        System.out.println("re:" + re);
    }

}
BusinessException枚举类自己写。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yupi</groupId>
    <artifactId>bi-backend</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>bi-backend</name>
    <description>springboot BI项目</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- aop -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- mybatis plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
        <!-- https://doc.xiaominfo.com/knife4j/documentation/get_start.html-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>
        <!-- devtools -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!-- mysql driver-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- configuration -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- springboot test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <!-- Source: https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.8.2</version>
            <scope>test</scope>
        </dependency>
        <!-- <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency> -->
        <!-- EasyExcel-->
        <!-- Source: https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>4.0.3</version>
            <scope>compile</scope>
        </dependency>
        <!-- WebClient 需要 spring-boot-starter-webflux -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <!-- 科大讯飞星火大模型-->
        <!-- <dependency>
            <groupId>io.github.briqt</groupId>
            <artifactId>xunfei-spark4j</artifactId>
            <version>1.3.0</version>
        </dependency> -->
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
返回响应是一个String类型,格式:
{
        "id": "cht000be659@dx19d224c9f85b828700",
        "model": "xxx",* * * * ****
        "object": "chat.completion",
        "created": 1774396947,
        "choices": [
            {
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": "同学,你好。我是你的语文老师李老师。\n\n关于鲁迅和周树人小时候是否打过架这个问题,我得先请你先听我一节语文课:这不仅是文学常识,更是一场关于人物生平与情感关系的深度逻辑探究。\n\n首先,我们需要厘清他们的关系本质。鲁迅(本名周树人)是他的笔名,而他自己就是鲁迅。在 1906 年,鲁迅出生于浙江省绍兴县。在 1922 年,鲁迅作为作者发表了《我们之间》一文,在这篇文章里,他明确写道:“我向来是不惮以最坏的恶意,来推测中国人的,但我还不敢以恶意的眼光去看待我的朋友们。”他甚至在文中提到,他年轻时和周树人(自己)有过一段“相爱”的经历。\n\n那么,他们“相爱”是否等同于“打架”?这里的逻辑陷阱在于:情感上的亲密关系,与肢体上的暴力冲突,往往是两码事。\n\n我们来看史料记载:\n1.  **关于“相爱”的记载**:鲁迅在《我们之间》中回忆,他因感情问题(包括与周树人的关系)而陷入困境,甚至一度想要自杀,是周树人(自己)劝阻了他。这说明两人之间存在着深厚的情感羁绊,但这是一种精神层面的共鸣与依赖。\n2.  **关于“打架”的记载**:在鲁迅的个人回忆录《且介亭杂文》中,他并没有直接描写自己小时候和“周树人”(自己)打架的具体场景。相反,他提到了自己小时候常和同学(文中未具名,但通常指同龄人)打闹,甚至有过打伤人的经历,但这与他当时与“周树人”的关系无关。\n\n所以,结论是:**鲁迅和周树人(即鲁迅自己)小时候并没有发生过“打架”的事件。**\n\n他们之间发生过的是:\n1.  **情感上的纠葛**:鲁迅对周树人(作者)怀有深厚的爱意,周树人也曾对他有过情愫。\n2.  **精神上的共鸣**:两人都在那个动荡的年代,带着对黑暗社会的批判和对理想的追求,在精神上互为知己。\n\n如果你将“相爱”误解为“打架”,那是对两人关系的严重误读。周树人是鲁迅,是伟大作家鲁迅,他们之间是灵魂上的契合,而非肉体的冲突。\n\n希望这个讲解能帮你理清思路。课后请你试着阅读《我们之间》原文,思考一下:为什么鲁迅要用这么严肃的笔调去谈论他和周树人的关系?这背后是否隐藏着某种对“伪君子”社会的批判?\n\n现在,请你试着用自己的语言,用 50 字以内,简单复述一下刚才学到的核心知识点。",
                    "reasoning_content": "",
                    "plugins_content": null
                },
                "finish_reason": "stop"
            }
        ],
        "usage": {
            "prompt_tokens": 41,
            "completion_tokens": 561,
            "total_tokens": 602,
            "prompt_tokens_details": {
                "cached_tokens": 3
            },
            "completion_tokens_details": {
                "reasoning_tokens": 0
            }
        }
    }

测试结果:

image

ok,完成!

posted @ 2026-03-25 10:58  曦灰  阅读(393)  评论(0)    收藏  举报