Spring AI使用JSON Schema导致模型调用速度极慢

最近在开发一个基于 Spring AI 的 AI 项目。为了确保大模型返回的数据一定是结构化的 JSON 格式,我在调用时显式指定了 response_formatJSON_SCHEMA
到目前为止,效果确实不错,每次返回的都是合法 JSON,字段和类型完全符合预期。

代码大致是下面这种,配置了一个jsonSchema,每次调用大概在11秒左右,最快的时候8秒。

public String callAI(RequestDTO request) {
    String systemPrompt = TemplateReaderUtil.readTemplate("template/business-rule-template.md");

    // 构造对话上下文
    List<Message> messages = List.of(
        new SystemMessage(systemPrompt),
        new UserMessage(request.getInputText())
    );

    String jsonSchema = """
        {
          "type": "object",
          "properties": {
            "result": { "type": "integer", "minimum": 0, "maximum": 100 },
            "details": {
              "type": "object",
              "properties": {
                "metricA": { "type": "integer", "minimum": 0, "maximum": 30 },
                "metricB": { "type": "integer", "minimum": 0, "maximum": 25 },
                "metricC": { "type": "integer", "minimum": 0, "maximum": 20 },
              },
              "required": ["metricA", "metricB", "metricC"],
              "additionalProperties": false
            },
            "comment": { "type": "string", "maxLength": 100 }
          },
          "required": ["result", "details", "comment"],
          "additionalProperties": false
        }
        """;

    // 配置大模型请求:强制按 JSON Schema 输出
    Prompt prompt = new Prompt(messages, OpenAiChatOptions.builder()
        .responseFormat(new ResponseFormat(ResponseFormat.Type.jsonSchema , jsonSchema))
        .temperature(0.8)
        .topP(0.9)
        .build());

    ChatResponse response = chatModel.call(prompt);
    return response.getResults().get(0).getOutput().getText();
}

今天突发奇想,把prompt放在Cherry Studio里面直接用,发现只需要1秒左右就回答完毕,当时就觉得不对劲。拿着CS调整了是否流式输出等一些参数,发现还是很快。最后怀疑是这个jsonSchema的问题,就写了一个最简单的调用。发现调用速度也是在1秒左右。

    String call(RequestDTO request) {
        String systemPrompt = TemplateReaderUtil.readTemplate("template/business-rule-template.md");

        // 构造对话上下文
        List<Message> messages = List.of(
                new SystemMessage(systemPrompt),
                new UserMessage(request.getInputText())
        );
        Prompt prompt = new Prompt(messageList, OpenAiChatOptions.builder()
                .temperature(0.4)
                .topP(0.6)
                .build());
        ChatResponse chatResponse = chatModel.call(prompt);
        return chatResponse.getResults().get(0).getOutput().getText();
    }

最后,又验证了一下其他写法,把jsonSchema的值改了一下,依旧使用responseFormat。发现速度也很快。

也试了一下把type的值改成json_object,调用直接报错了,可能和使用的大模型也有关,我这次使用的Qwen

String jsonSchema = """
                {
                  "type": "object"
                }
                """;

所以为了速度,可以去掉jsonSchema,去掉之后大模型输出JSON的格式有时候会不稳定(比如输出会加上```json),这种要在后端处理一下。
也可以只配置一个type就行(注意测试不同模型type值是否会有差异)
只能说谨慎使用jsonSchema

posted @ 2025-12-09 18:07  西瓜当冬瓜  阅读(0)  评论(0)    收藏  举报