开发者如何调用AI模型

一直觉得调用 AI 很麻烦,也没有实践过,在 V2EX 上提问后 打算自己实践下,发现特别简单哪怕是刚刚学会代码的人都可以快速的进行调用.

现在网上超级多的如何使用 AI 方便自己的工作,但是很多的教程都只是 AI Chat 页面让AI 进行 Markdown 的返回然后再手动处理,并没有达到我想要的结果,所有查看文档后发现了有 JSON Output 输出方案.那么我这边就以 DeepSeek 为例子调用 使用 Java API 并返回结果.

调用流程

准备内容

  1. DeepSeek API Key sk-07f4d2117ddb495ba57959941186ac93
  2. Java 环境(谁的环境都行只要能调用 HTTP 接口即可)

业务

这边的业务是用户传递一段文字包含题目和答案,需要使用 AI 将题目和答案进行区分并使用特定的 JSON 结构进行返回数据.

例如:

执行

准备系统提示词

系统提示词相当于是你写的代码,你系统提示词写的越好其返回的结构就越标准.

用户将提供一些考试文本. 请解析"问题"和"答案",并以json格式输出。 
例如输入: 世界上最高的人是?高晓松.
例如输出: 
{
    "question": "世界上最高的人是?",
    "answer": "高晓松"
}

准备用户问题

世界最高的山是?珠穆拉峰.

代码原理

准备 HTTP 请求条件,其中最重要的就是 response_format 需要将其改为 json_object 其他就是格式的 context ,要求 API 返回的是 JSON 对象.详细代码在后面附加.

{
    "frequency_penalty": 0,
    "logprobs": false,
    "max_tokens": 4096,
    "messages": [
        {
            "content": "用户将提供一些考试文本. 请解析\"问题\"和\"答案\",并以json格式输出。 \n\n例如输入: \n世界上最高的人是?高晓松.\n\n例如输出:\n{\n    \"question\": \"世界上最高的人是?\",\n    \"answer\": \"高晓松\"\n}",
            "role": "system"
        },
        {
            "content": "世界最高的山是?珠穆拉峰",
            "role": "user"
        }
    ],
    "model": "deepseek-chat",
    "presence_penalty": 0,
    "response_format": {
        "type": "json_object"
    },
    "stream": false,
    "temperature": 1,
    "tool_choice": "none",
    "top_p": 1
}

通过该内容进行提交 HTTP 接口即可返回内容 在 message content 中已经看到了其将内容已经拆分通过该返回再进行业务处理.

{
    "id": "192aebaa-7d50-4e9f-8a0a-7123254fcb25",
    "object": "chat.completion",
    "created": 1740017912,
    "model": "deepseek-chat",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "{\n    \"question\": \"世界最高的山是?\",\n    \"answer\": \"珠穆拉峰\"\n}"
            },
            "logprobs": null,
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 81,
        "completion_tokens": 27,
        "total_tokens": 108,
        "prompt_tokens_details": {
            "cached_tokens": 64
        },
        "prompt_cache_hit_tokens": 64,
        "prompt_cache_miss_tokens": 17
    },
    "system_fingerprint": "fp_3a5770e1b4"
}

注意

  1. 响应速度慢: 因为采用了 API 调用返回并不是 流式 返回所有如果你的返回信息需要与用户交互则需要使用 流返回 修改 stream.如果你只是调用 API 那么建议采用异步的方式进行返回从而提高使用体验.
  2. 响应数据库长度: 在 DeepSeek 中使用每个 API 接口可以返回的 Token 数即 max_tokens 最高是 8192 在转换成英文的情况下是 2.5w 字符左右.如果是中文的话也就在 1.25w 字左右.

文档

代码

DeepSeekRequest.class

package org.example;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @Author : PeiXinyi
 * @Date : 2025/2/20 09:37
 * @Version : 0.0.0
 */
@NoArgsConstructor
@Data
public class DeepSeekRequest {

    @JsonProperty("messages")
    private List<MessagesDTO> messages;
    @JsonProperty("model")
    private String model;
    @JsonProperty("frequency_penalty")
    private Integer frequencyPenalty;
    @JsonProperty("max_tokens")
    private Integer maxTokens;
    @JsonProperty("presence_penalty")
    private Integer presencePenalty;
    @JsonProperty("response_format")
    private ResponseFormatDTO responseFormat;
    @JsonProperty("stop")
    private Object stop;
    @JsonProperty("stream")
    private Boolean stream;
    @JsonProperty("stream_options")
    private Object streamOptions;
    @JsonProperty("temperature")
    private Integer temperature;
    @JsonProperty("top_p")
    private Integer topP;
    @JsonProperty("tools")
    private Object tools;
    @JsonProperty("tool_choice")
    private String toolChoice;
    @JsonProperty("logprobs")
    private Boolean logprobs;
    @JsonProperty("top_logprobs")
    private Object topLogprobs;

    @NoArgsConstructor
    @Data
    public static class ResponseFormatDTO {
        @JsonProperty("type")
        private String type;

        public ResponseFormatDTO(String type) {
            this.type = type;
        }
    }

    @NoArgsConstructor
    @Data
    public static class MessagesDTO {
        @JsonProperty("content")
        private String content;
        @JsonProperty("role")
        private String role;


        public MessagesDTO(String content, String role) {
            this.content = content;
            this.role = role;
        }
    }

}

DeepSeekResponse

package org.example;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @Author : PeiXinyi
 * @Date : 2025/2/20 09:46
 * @Version : 0.0.0
 */
@NoArgsConstructor
@Data
public class DeepSeekResponse {

    @JsonProperty("id")
    private String id;
    @JsonProperty("object")
    private String object;
    @JsonProperty("created")
    private Integer created;
    @JsonProperty("model")
    private String model;
    @JsonProperty("choices")
    private List<ChoicesDTO> choices;
    @JsonProperty("usage")
    private UsageDTO usage;
    @JsonProperty("system_fingerprint")
    private String systemFingerprint;

    @NoArgsConstructor
    @Data
    public static class UsageDTO {
        @JsonProperty("prompt_tokens")
        private Integer promptTokens;
        @JsonProperty("completion_tokens")
        private Integer completionTokens;
        @JsonProperty("total_tokens")
        private Integer totalTokens;
        @JsonProperty("prompt_tokens_details")
        private PromptTokensDetailsDTO promptTokensDetails;
        @JsonProperty("prompt_cache_hit_tokens")
        private Integer promptCacheHitTokens;
        @JsonProperty("prompt_cache_miss_tokens")
        private Integer promptCacheMissTokens;

        @NoArgsConstructor
        @Data
        public static class PromptTokensDetailsDTO {
            @JsonProperty("cached_tokens")
            private Integer cachedTokens;
        }
    }

    @NoArgsConstructor
    @Data
    public static class ChoicesDTO {
        @JsonProperty("index")
        private Integer index;
        @JsonProperty("message")
        private MessageDTO message;
        @JsonProperty("logprobs")
        private Object logprobs;
        @JsonProperty("finish_reason")
        private String finishReason;

        @NoArgsConstructor
        @Data
        public static class MessageDTO {
            @JsonProperty("role")
            private String role;
            @JsonProperty("content")
            private String content;
        }
    }
}

ApplicationRun

package org.example;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.util.Arrays;


/**
 * @Author : PeiXinyi
 * @Date : 2024/8/15 11:25
 * @Version : V1.0
 */
@Slf4j
public class ApplicationRun {
    public static void main(String[] args) throws IOException {
        String systemMessage = "用户将提供一些考试文本. 请解析\"问题\"和\"答案\",并以json格式输出。 \n\n例如输入: \n世界上最高的人是?高晓松.\n\n例如输出:\n{\n    \"question\": \"世界上最高的人是?\",\n    \"answer\": \"高晓松\"\n}";
        String userMessage = "世界最高的山是?珠穆拉峰";

        DeepSeekRequest.MessagesDTO systemRole = new DeepSeekRequest.MessagesDTO(systemMessage, "system");
        DeepSeekRequest.MessagesDTO userRole = new DeepSeekRequest.MessagesDTO(userMessage, "user");

        DeepSeekRequest request = new DeepSeekRequest();
        DeepSeekRequest.ResponseFormatDTO responseFormatDTO = new DeepSeekRequest.ResponseFormatDTO("json_object");


        request.setMessages(Arrays.asList(systemRole, userRole));
        request.setModel("deepseek-chat");
        request.setFrequencyPenalty(0);
        request.setMaxTokens(4096);
        request.setPresencePenalty(0);
        request.setResponseFormat(responseFormatDTO);
        request.setStream(false);
        request.setTemperature(1);
        request.setTopP(1);
        request.setToolChoice("none");
        request.setLogprobs(false);

        System.out.println(JSON.toJSONString(request));

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONBytes(request));
        Request httpRequest = new Request.Builder()
                .url("https://api.deepseek.com/chat/completions")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer sk-07f4d2117ddb495ba57959941186ac93")
                .build();
        Response response = client.newCall(httpRequest).execute();
        System.out.println("---------");
        System.out.println(response.body().string());
    }


}