智谱api接口调用(Java调用文本模型,文生图,文生视,代码助手等)

1.进入智谱AI开发平台

智谱AI开放平台,点击进入到官网,注册好账号后登录即可,那么就会有朋友问,调用api是不是要钱?那是一定要滴!不然工资谁发?当然!我们新用户是有很多的试用tokens数的,那么为了大家调用方便,开发文档就不带大家看了,大家只需要通过我的代码替换掉我的API就可以体验了。

2.创建API key

在智谱AI顶部,按照下图顺序进行操作,添加好后,替换我的API即可(温馨提示自己的api不要泄露,tokens数一旦超了就会扣费了,部分模型是有调用次数限制的,但是文本大模型放心用!新用户文生视(根据文字生成视频,是有400次的),因此大家要勒紧好自己的裤腰带哈!不过放心,你可以在顶部导航栏找到“财务”,详细查看使用情况,其中“资源包管理”中,就是显示你剩余的tokens余额和到期时间

3.在IDEA中创建一个project,命名随意,可以参照我的

演示环境

操作系统:Windows 11

IDEA版本:IntelliJ IDEA 2023.3.8

maven:apache-maven-3.8.1

4.代码分享

4.1 CloudEduAssistant
package com.lorn.edu.ai;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CloudEduAssistant {
    private static final String ASSISTANT_NAME = "替换为您的xxx助手";
    private static final String WELCOME_MESSAGE =
            "欢迎使用xxx智能助手!我是您的专属学习伙伴,可以为您提供以下服务:\n" +
                    "1. 编程技术指导和代码优化\n" +
                    "2. 算法讲解和数据结构分析\n" +
                    "3. 学习方法和规划建议\n" +
                    "4. 知识解答和概念讲解\n" +
                    "输入'帮助'可以查看更多功能,输入'退出'结束对话。";

    private static final boolean IMAGE_GENERATION_ENABLED = true;
    private static final boolean VIDEO_GENERATION_ENABLED = true;

    private final ChatService chatService;
    private final ImageService imageService;
    private final VideoService videoService;
    private final CodeService codeService;
    private final OnlineCodeService onlineCodeService;
    private final List<JSONObject> messages;
    private boolean isCodeMode = false;
    private boolean isInteractiveMode = false;
    private final Scanner scanner;

    public CloudEduAssistant() {
        this.chatService = new ChatService();
        this.imageService = new ImageService();
        this.videoService = new VideoService();
        this.codeService = new CodeService();
        this.onlineCodeService = new OnlineCodeService();
        this.messages = new ArrayList<>();
        this.scanner = new Scanner(System.in);
    }

    public void start() throws Exception {
        System.out.println("\n=== " + ASSISTANT_NAME + " ===");
        System.out.println(WELCOME_MESSAGE);
        System.out.println("============================\n");

        while (true) {
            System.out.print("你: ");
            String userInput = scanner.nextLine();

            if (userInput == null || userInput.trim().isEmpty()) {
                System.out.println("输入不能为空,请重新输入!");
                continue;
            }

            if (handleSpecialCommands(userInput)) {
                continue;
            }

            processUserInput(userInput);
        }
    }

    private boolean handleSpecialCommands(String input) throws Exception {
        if (input.toLowerCase().startsWith("画图 ") ||
                input.toLowerCase().startsWith("生成图片 ") ||
                input.toLowerCase().startsWith("图片 ") ||
                input.toLowerCase().startsWith("图 ")) {
            String prompt = input.substring(input.indexOf(" ")).trim();
            handleImageGeneration(prompt);
            return true;
        }

        if (input.equalsIgnoreCase("图片")) {
            System.out.println(ASSISTANT_NAME + ": 请在'图片'后面添加描述,例如:");
            System.out.println("- 图片 一只可爱的小狗");
            System.out.println("- 图 蓝天白云下的草原");
            System.out.println("- 画图 夕阳下的海滩");
            return true;
        }

        if (input.toLowerCase().startsWith("视频 ")) {
            handleVideoGeneration(input.substring(3).trim());
            return true;
        }

        switch (input.toLowerCase()) {
            case "退出":
                System.out.println("感谢使用" + ASSISTANT_NAME + ",再见!");
                System.exit(0);
                return true;
            case "清空":
                messages.clear();
                System.out.println("对话历史已清空!");
                return true;
            case "帮助":
                showHelp();
                return true;
            case "切换代码模式":
                isCodeMode = true;
                System.out.println(ASSISTANT_NAME + ": 已切换到代码问答模式 (CodeGeeX-4)");
                return true;
            case "切换聊天模式":
                isCodeMode = false;
                System.out.println(ASSISTANT_NAME + ": 已切换到通用聊天模式 (GLM-4)");
                return true;
            case "分析代码":
                handleCodeAnalysis();
                return true;
            case "优化代码":
                handleCodeOptimization();
                return true;
            case "运行代码":
                handleCodeExecution();
                return true;
            case "交互模式":
                handleInteractiveMode();
                return true;
            default:
                return false;
        }
    }

    private void processUserInput(String input) {
        try {
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", "user");
            userMessage.put("content", input);
            messages.add(userMessage);

            String response;
            if (isCodeMode) {
                response = codeService.askCodingQuestion(messages);
            } else {
                response = chatService.sendMessage(messages);
            }

            System.out.println(ASSISTANT_NAME + ": " + response);

            JSONObject assistantMessage = new JSONObject();
            assistantMessage.put("role", "assistant");
            assistantMessage.put("content", response);
            messages.add(assistantMessage);
        } catch (Exception e) {
            System.out.println("发送消息失败: " + e.getMessage());
        }
    }

    private void handleImageGeneration(String prompt) {
        if (!IMAGE_GENERATION_ENABLED) {
            System.out.println(ASSISTANT_NAME + ": 抱歉,图片生成功能当前不可用。");
            System.out.println(ASSISTANT_NAME + ": 原因:需要开通专门的图片生成服务额度。");
            System.out.println(ASSISTANT_NAME + ": 您可以:");
            System.out.println("1. 访问智谱AI官网开通图片生成服务");
            System.out.println("2. 使用其他功能,如聊天、代码分析等");
            return;
        }

        try {
            System.out.println(ASSISTANT_NAME + ": 开始生成图片...");
            System.out.println(ASSISTANT_NAME + ": 正在处理提示词: " + prompt);
            String imagePath = imageService.generateImage(prompt);
            System.out.println(ASSISTANT_NAME + ": 图片已生生成并保存到: " + imagePath);
        } catch (Exception e) {
            System.out.println("图片生成失败: " + e.getMessage());
            if (e.getMessage().contains("欠费") || e.getMessage().contains("1113")) {
                System.out.println(ASSISTANT_NAME + ": 图片生成服务需要单独开通和计费。");
                System.out.println(ASSISTANT_NAME + ": 请访问智谱AI官网开通相关服务。");
            }
            e.printStackTrace();
        }
    }

    private void handleVideoGeneration(String prompt) {
        if (!VIDEO_GENERATION_ENABLED) {
            System.out.println(ASSISTANT_NAME + ": 抱歉,视频生成功能当前不可用。");
            System.out.println(ASSISTANT_NAME + ": 原因:需要开通专门的视频生成服务额度。");
            System.out.println(ASSISTANT_NAME + ": 您可以:");
            System.out.println("1. 访问智谱AI官网开通视频生成服务");
            System.out.println("2. 使用其他功能,如聊天、代码分析等");
            return;
        }

        try {
            System.out.println(ASSISTANT_NAME + ": 开始生成视频,这可能需要几分钟时间...");
            System.out.println(ASSISTANT_NAME + ": 视频生成过程中请勿退出程序,生成完成后会自动保存");
            String videoPath = videoService.generateVideo(prompt);
            System.out.println(ASSISTANT_NAME + ": 视频已生成并保存到: " + videoPath);
        } catch (Exception e) {
            System.out.println("视频生成失败: " + e.getMessage());
            System.out.println("如果是超时错误,视频可能仍在生成中,请稍后再试。");
        }
    }

    private void handleCodeAnalysis() throws Exception {
        System.out.println(ASSISTANT_NAME + ": 请输入要分析的代码(输入'完成'结束):");
        StringBuilder code = new StringBuilder();
        while (true) {
            String line = scanner.nextLine();
            if (line.equals("完成")) break;
            code.append(line).append("\n");
        }
        String result = codeService.analyzeCode(code.toString());
        System.out.println(ASSISTANT_NAME + ": " + result);
    }

    private void handleCodeOptimization() throws Exception {
        System.out.println(ASSISTANT_NAME + ": 请输入要优化的代码(输入'完成'结束):");
        StringBuilder code = new StringBuilder();
        while (true) {
            String line = scanner.nextLine();
            if (line.equals("完成")) break;
            code.append(line).append("\n");
        }
        String result = codeService.optimizeCode(code.toString());
        System.out.println(ASSISTANT_NAME + ": " + result);
    }

    private void handleCodeExecution() throws Exception {
        System.out.println(ASSISTANT_NAME + ": 请选择编程语言:");
        System.out.println("1. Java");
        System.out.println("2. Python");
        System.out.println("3. C++");

        String language = scanner.nextLine().toLowerCase();
        String langCode = "";

        switch (language) {
            case "1":
            case "java":
                langCode = "java";
                break;
            case "2":
            case "python":
                langCode = "python3";
                break;
            case "3":
            case "c++":
                langCode = "cpp";
                break;
            default:
                System.out.println("不支持的语言!");
                return;
        }

        System.out.println(ASSISTANT_NAME + ": 请输入代码(输入'完成'结束):");
        StringBuilder code = new StringBuilder();
        while (true) {
            String line = scanner.nextLine();
            if (line.equals("完成")) break;
            code.append(line).append("\n");
        }

        try {
            String result = onlineCodeService.executeCode(code.toString(), langCode, "0");
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("代码执行失败: " + e.getMessage());
        }
    }

    private void handleInteractiveMode() {
        System.out.println(ASSISTANT_NAME + ": 进入代码执行模式");
        System.out.println("请选择编程语言:");
        System.out.println("1. Java");
        System.out.println("2. Python");
        System.out.println("3. C++");

        String language = scanner.nextLine().toLowerCase();
        String langCode = "";

        switch (language) {
            case "1":
            case "java":
                langCode = "java";
                break;
            case "2":
            case "python":
                langCode = "python3";
                break;
            case "3":
            case "c++":
                langCode = "cpp";
                break;
            default:
                System.out.println("不支持的语言!");
                return;
        }

        while (true) {
            System.out.println(ASSISTANT_NAME + ": 请输入代码(输入'退出'结束,输入'运行'执行):");
            StringBuilder code = new StringBuilder();

            while (true) {
                String line = scanner.nextLine();
                if (line.equals("退出")) {
                    return;
                }
                if (line.equals("运行")) {
                    break;
                }
                code.append(line).append("\n");
            }

            try {
                String result = onlineCodeService.executeCode(code.toString(), langCode, "0");
                System.out.println(result);
            } catch (Exception e) {
                System.out.println("代码执行失败: " + e.getMessage());
            }
        }
    }

    private void showHelp() {
        System.out.println("\n=== " + ASSISTANT_NAME + " 功能说明 ===");
        System.out.println("1. 基础对话:直接输入问题即可");
        System.out.println("2. 图片生成:" + (IMAGE_GENERATION_ENABLED ? "可用" : "暂不可用"));
        System.out.println("   - 使用方法:");
        System.out.println("     图片 [描述]  (例如:图片 一只可爱的小狗)");
        System.out.println("     图 [描述]    (例如:图 蓝天白云)");
        System.out.println("     画图 [描述]  (例如:画图 夕阳海滩)");
        System.out.println("3. 视频生成:" + (VIDEO_GENERATION_ENABLED ? "可用" : "暂不可用"));
        System.out.println("4. 代码功能:");
        System.out.println("   - 切换代码模式:使用CodeGeeX-4进行代码问答");
        System.out.println("   - 分析代码:分析代码并提供改进建议");
        System.out.println("   - 优化代码:优化代码并解释原因");
        System.out.println("   - 运行代码:在线运行代码");
        System.out.println("   - 交互模式:交互式编程环境");
        System.out.println("5. 其他命令:");
        System.out.println("   - 帮助:显示本帮助信息");
        System.out.println("   - 清空:清除对话历史");
        System.out.println("   - 退出:结束对话");
        System.out.println("============================\n");
    }

    public void close() {
        if (scanner != null) {
            scanner.close();
        }
    }

    public static void main(String[] args) throws Exception {
        CloudEduAssistant assistant = new CloudEduAssistant();
        try {
            assistant.start();
        } finally {
            assistant.close();
        }
    }
}

4.2 ChatService

package com.lorn.edu.ai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class ChatService {
    private static final String API_KEY = "替换为您的API key";
    private static final String API_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
    private ModelType currentModel;
    private final OkHttpClient client;

    public enum ModelType {
        GLM4("glm-4"),
        GLM4PLUS("glm-4-plus"),
        CODEGEEX4("codegeex-4");

        private final String value;

        ModelType(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    public ChatService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        this.currentModel = ModelType.CODEGEEX4; // 默认使用 CodeGeeX-4
    }

    public void setModel(ModelType model) {
        this.currentModel = model;
    }

    public String sendMessage(List<JSONObject> messages) throws Exception {
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", currentModel.getValue());
        
        // 处理消息编码
        List<JSONObject> encodedMessages = new ArrayList<>();
        for (JSONObject msg : messages) {
            JSONObject encodedMsg = new JSONObject();
            encodedMsg.put("role", msg.getString("role"));
            String content = msg.getString("content");
            // 确保内容使用 UTF-8 编码
            encodedMsg.put("content", new String(content.getBytes("UTF-8"), "UTF-8"));
            encodedMessages.add(encodedMsg);
        }
        requestBody.put("messages", encodedMessages);

        // 设置模型参数
        if (currentModel == ModelType.CODEGEEX4) {
            requestBody.put("temperature", 0.8);
            requestBody.put("top_p", 0.8);
            requestBody.put("stream", false);
            requestBody.put("max_tokens", 2048);
            requestBody.put("stop", new String[]{"<|user|>", "<|assistant|>"});
        } else {
            // GLM4 和 GLM4PLUS 的参数
            requestBody.put("temperature", 0.7);
            requestBody.put("stream", false);
        }

        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .post(RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"), 
                    requestBody.toString()
                ))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败,状态码: " + response.code());
            }

            String responseBody = response.body().string();
            JSONObject jsonResponse = JSON.parseObject(responseBody);
            String content = jsonResponse.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");
                    
            // 确保返回内容使用正确的编码
            return new String(content.getBytes("UTF-8"), "UTF-8");
        }
    }
}

4.3 GLMChatService

package com.lorn.edu.ai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class GLMChatService {
    private static final String API_KEY = "替换为您的API key";
    private static final String API_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
    private final OkHttpClient client;

    public GLMChatService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    public String chat(List<JSONObject> messages) throws Exception {
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "glm-4-plus");
        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);
        requestBody.put("stream", false);

        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .post(RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"), 
                    requestBody.toString()
                ))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败,状态码: " + response.code());
            }

            String responseBody = response.body().string();
            JSONObject jsonResponse = JSON.parseObject(responseBody);
            return jsonResponse.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");
        }
    }

    public String getSystemPrompt() {
        return "你是一个xxx团队精心打造的xxx助手,专注于提供专业、友好的对话服务。" +
               "你的回答应该简洁明了,直接回应用户的问题。" +
               "如果遇到不明确的问题,请礼貌地请求用户提供更多信息。" +
               "你应该表现出对话的连贯性和上下文理解能力。";
    }
} 

4.4 CodeService

package com.lorn.edu.ai;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class CodeService {
    private static final String API_KEY = "替换为您的API key";
    private static final String API_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
    private static final String MODEL = "codegeex-4";

    private final OkHttpClient client;

    public CodeService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    public String askCodingQuestion(List<JSONObject> messages) throws Exception {
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", MODEL);
        requestBody.put("messages", messages);

        // CodeGeeX-4特定参数
        requestBody.put("temperature", 0.8);
        requestBody.put("top_p", 0.8);
        requestBody.put("stream", false);
        requestBody.put("max_tokens", 2048);
        requestBody.put("stop", new String[]{"<|user|>", "<|assistant|>"});

        System.out.println("代码问答请求体: " + requestBody.toString());

        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(MediaType.parse("application/json"), requestBody.toString()))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败,状态码: " + response.code());
            }

            String responseBody = response.body().string();
            System.out.println("代码问答响应: " + responseBody);

            JSONObject jsonResponse = JSON.parseObject(responseBody);
            return jsonResponse.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");
        }
    }

    // 添加代码分析功能
    public String analyzeCode(String code) throws Exception {
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", "请分析以下代码并指出可能的改进点:\n\n" + code);

        List<JSONObject> messages = new ArrayList<>();
        messages.add(message);

        return askCodingQuestion(messages);
    }

    // 添加代码优化功能
    public String optimizeCode(String code) throws Exception {
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", "请优化以下代码,并解释优化原因:\n\n" + code);

        List<JSONObject> messages = new ArrayList<>();
        messages.add(message);

        return askCodingQuestion(messages);
    }
}

4.5  ImageService

package com.lorn.edu.ai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ImageService {
    private static final String API_KEY = "替换为您的API key";
    private static final String API_URL = "https://open.bigmodel.cn/api/paas/v4/images/generations";
    private static final String IMAGE_SAVE_PATH = "E:\\WorkSpace\\cloud_resource\\static\\images\\";//将所生成的图片保存到您的本地磁盘
    // 文生图使用示例   如:图片 一条哈士奇睡在沙发上

    private static final int MAX_RETRIES = 3;
    private static final long RETRY_INTERVAL = 5000; // 5秒

    // 修改默认模型为cogview-3-plus
    private static final String DEFAULT_MODEL = "cogview-3-plus";

    // 支持的图片尺寸
    public enum ImageSize {
        DEFAULT("1024x1024"),
        PORTRAIT_LARGE("768x1344"),
        PORTRAIT_MEDIUM("864x1152"),
        LANDSCAPE_LARGE("1344x768"),
        LANDSCAPE_MEDIUM("1152x864"),
        LANDSCAPE_WIDE("1440x720"),
        PORTRAIT_WIDE("720x1440");

        private final String value;

        ImageSize(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    private final OkHttpClient client;

    public ImageService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    public String generateImage(String prompt) throws Exception {
        // 使用cogview-3-plus作为默认模型
        return generateImage(prompt, DEFAULT_MODEL, ImageSize.DEFAULT);
    }

    public String generateImage(String prompt, String model, ImageSize size) throws Exception {
        Exception lastException = null;

        for (int attempt = 0; attempt < MAX_RETRIES; attempt++) {
            try {
                if (attempt > 0) {
                    System.out.println("等待" + (RETRY_INTERVAL/1000) + "秒后进行第" + (attempt + 1) + "次尝试...");
                    Thread.sleep(RETRY_INTERVAL);
                }

                // 准备请求体
                JSONObject requestBody = new JSONObject();
                requestBody.put("model", model);
                requestBody.put("prompt", prompt);

                // cogview-3-plus总是支持size参数
                requestBody.put("size", size.getValue());

                System.out.println("生成图片请求体: " + requestBody.toString());

                Request request = new Request.Builder()
                        .url(API_URL)
                        .addHeader("Authorization", "Bearer " + API_KEY)
                        .addHeader("Content-Type", "application/json")
                        .post(RequestBody.create(MediaType.parse("application/json"), requestBody.toString()))
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    String responseBody = response.body() != null ? response.body().string() : "";
                    System.out.println("服务器响应: " + responseBody);

                    if (!response.isSuccessful()) {
                        JSONObject errorJson = JSON.parseObject(responseBody);
                        if (errorJson.containsKey("error")) {
                            JSONObject error = errorJson.getJSONObject("error");
                            String errorCode = error.getString("code");
                            String errorMessage = error.getString("message");

                            // 处理特定错误码
                            switch (errorCode) {
                                case "1113": // 欠费错误
                                    throw new Exception("API账户状态异常: " + errorMessage);
                                case "429": // 频率限制
                                    if (attempt < MAX_RETRIES - 1) {
                                        System.out.println("触发频率限制,将在" + (RETRY_INTERVAL/1000) + "秒后重试...");
                                        continue;
                                    }
                                    throw new Exception("请求频率过高,请稍后再试");
                                default:
                                    throw new Exception("API错误: " + errorMessage);
                            }
                        }
                        throw new IOException("请求失败,状态码: " + response.code());
                    }

                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    String imageUrl = jsonResponse.getJSONArray("data")
                            .getJSONObject(0)
                            .getString("url");

                    System.out.println("获取到图片URL: " + imageUrl);
                    return downloadAndSaveImage(imageUrl);
                }
            } catch (Exception e) {
                lastException = e;
                if (attempt == MAX_RETRIES - 1) {
                    throw new Exception("图片生成失败(尝试" + MAX_RETRIES + "次后): " + e.getMessage(), e);
                }
                System.out.println("第" + (attempt + 1) + "次尝试失败: " + e.getMessage());
            }
        }

        throw lastException;
    }

    private String downloadAndSaveImage(String imageUrl) throws Exception {
        Request request = new Request.Builder().url(imageUrl).build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("下载失败,状态码: " + response.code());
            }

            File directory = new File(IMAGE_SAVE_PATH);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            String timestamp = new java.text.SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(new java.util.Date());
            String fileName = IMAGE_SAVE_PATH + "image_" + timestamp + ".png";

            try (java.io.FileOutputStream fos = new java.io.FileOutputStream(fileName)) {
                fos.write(response.body().bytes());
            }

            System.out.println("图片已保存到: " + fileName);
            return fileName;
        }
    }
}

4.6 VideoService

package com.lorn.edu.ai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class VideoService {
    private static final String API_KEY = "替换为您的API key";
    private static final String GENERATE_API_URL = "https://open.bigmodel.cn/api/paas/v4/videos/generations";
    private static final String QUERY_API_URL = "https://open.bigmodel.cn/api/paas/v4/async-result";
    private static final String VIDEO_SAVE_PATH = "E:\\WorkSpace\\cloud_resource\\static\\videos\\";//将所生成的视频保存到您的本地磁盘
    //文生视使用示例   如:视频 一只小狗在开心的奔跑

    private final OkHttpClient client;
    private static final long QUERY_INTERVAL = 10000; // 10秒
    private static final int MAX_QUERY_TIMES = 60; // 10分钟

    public VideoService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
                .writeTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    public String generateVideo(String prompt) throws Exception {
        return generateVideo(prompt, null);
    }

    public String generateVideo(String prompt, String imageUrl) throws Exception {
        // 生成请求ID
        String requestId = UUID.randomUUID().toString();
        System.out.println("开始生成视频,请求ID: " + requestId);

        // 准备请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "cogvideox");
        requestBody.put("prompt", prompt);
        requestBody.put("request_id", requestId);

        if (imageUrl != null && !imageUrl.trim().isEmpty()) {
            requestBody.put("image_url", imageUrl);
        }

        System.out.println("生成请求体: " + requestBody.toString());

        // 发送生成请求
        Request request = new Request.Builder()
                .url(GENERATE_API_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(MediaType.parse("application/json"), requestBody.toString()))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("视频生成请求失败,状态码: " + response.code());
            }

            JSONObject jsonResponse = JSON.parseObject(response.body().string());
            String taskId = jsonResponse.getString("id");

            // 轮询查询结果
            return pollVideoResult(taskId);
        }
    }

    private String pollVideoResult(String taskId) throws Exception {
        System.out.println("获取到任务ID: " + taskId);

        for (int i = 0; i < MAX_QUERY_TIMES; i++) {
            Thread.sleep(QUERY_INTERVAL);

            // 构建查询URL
            String queryUrl = QUERY_API_URL + "/" + taskId;
            System.out.println("第" + (i + 1) + "次查询,URL: " + queryUrl);

            Request request = new Request.Builder()
                    .url(queryUrl)
                    .addHeader("Authorization", "Bearer " + API_KEY)
                    .get()
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String responseBody = response.body().string();
                System.out.println("查询响应: " + responseBody);

                if (!response.isSuccessful()) {
                    if (i < MAX_QUERY_TIMES - 1) {
                        System.out.println("查询失败,将在" + (QUERY_INTERVAL / 1000) + "秒后重试...");
                        continue;
                    }
                    throw new IOException("查询请求失败,状态码: " + response.code());
                }

                JSONObject jsonResponse = JSON.parseObject(responseBody);
                String status = jsonResponse.getString("task_status");
                System.out.println("任务状态: " + status);

                switch (status) {
                    case "SUCCESS":
                        // 从video_result数组中获取视频URL
                        JSONObject videoResult = jsonResponse.getJSONArray("video_result")
                                .getJSONObject(0);
                        String videoUrl = videoResult.getString("url");
                        String coverUrl = videoResult.getString("cover_image_url");

                        System.out.println("视频生成成功!");
                        System.out.println("视频URL: " + videoUrl);
                        System.out.println("封面URL: " + coverUrl);

                        return downloadAndSaveVideo(videoUrl);

                    case "FAIL":
                        String errorMessage = jsonResponse.containsKey("error") ?
                                jsonResponse.getString("error") : "未知错误";
                        throw new Exception("视频生成失败: " + errorMessage);

                    case "PROCESSING":
                        System.out.println("视频正在生成中,已等待" +
                                (i + 1) * (QUERY_INTERVAL / 1000) + "秒...");
                        continue;

                    default:
                        throw new Exception("未知的任务状态: " + status);
                }
            } catch (Exception e) {
                if (i == MAX_QUERY_TIMES - 1) {
                    throw e;
                }
                System.out.println("查询出错: " + e.getMessage());
            }
        }

        throw new Exception("视频生成超时,请稍后使用相同的请求ID重试");
    }

    private String downloadAndSaveVideo(String videoUrl) throws Exception {
        Request request = new Request.Builder().url(videoUrl).build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("视频下载失败,状态码: " + response.code());
            }

            File directory = new File(VIDEO_SAVE_PATH);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            String timestamp = new java.text.SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(new java.util.Date());
            String fileName = VIDEO_SAVE_PATH + "video_" + timestamp + ".mp4";

            try (java.io.FileOutputStream fos = new java.io.FileOutputStream(fileName)) {
                fos.write(response.body().bytes());
            }

            return fileName;
        }
    }
}

4.7 OnlineCodeService

package com.lorn.edu.ai;

import com.alibaba.fastjson.JSONObject;

import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class OnlineCodeService {
    private final ChatService chatService;
    private final ExecutorService executorService;

    public OnlineCodeService() {
        this.chatService = new ChatService();
        this.chatService.setModel(ChatService.ModelType.CODEGEEX4);
        this.executorService = Executors.newCachedThreadPool();
    }

    public String executeCode(String code, String language, String versionIndex) throws Exception {
        // 创建一个空的历史记录列表
        List<JSONObject> emptyHistory = new ArrayList<>();
        // 构建默认的分析消息
        String defaultMessage = "请执行这段代码并返回运行结果。如果有错误,请指出错误并给出修改建议。";
        return executeCode(code, language, defaultMessage, emptyHistory);
    }

    public String executeCode(String code, String language, String message, List<JSONObject> history) throws Exception {
        List<JSONObject> messages = new ArrayList<>();
        
        // 添加系统角色提示
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");
        systemMessage.put("content", "你是一个代码执行助手。请执行用户提供的代码并返回运行结果。" +
                "如果代码有错误,请指出错误并给出修改建议。" +
                "请专注于代码分析和执行,提供专业的技术建议。");
        messages.add(systemMessage);

        // 添加历史消息
        if (history != null) {
            messages.addAll(history);
        }

        // 构建当前消息
        StringBuilder prompt = new StringBuilder();
        prompt.append("请执行以下").append(language).append("代码并返回运行结果:\n\n");
        prompt.append("```").append(language).append("\n");
        prompt.append(code).append("\n");
        prompt.append("```");

        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", prompt.toString());
        messages.add(userMessage);

        // 使用 CodeGeeX-4 生成回复
        String response = chatService.sendMessage(messages);
        
        // 格式化输出结果
        return formatExecutionResult(response);
    }

    private String formatExecutionResult(String aiResponse) {
        StringBuilder result = new StringBuilder();
        
        // 提取代码执行结果
        String[] parts = aiResponse.split("```");
        if (parts.length > 1) {
            // 提取实际的执行结果,去除多余的语言标记
            String output = parts[1].trim();
            if (output.startsWith("java") || output.startsWith("python") || output.startsWith("cpp")) {
                output = output.substring(output.indexOf("\n") + 1).trim();
            }
            result.append(output);
            
            // 如果有编译错误或警告,添加到结果中
            if (aiResponse.contains("错误") || aiResponse.contains("警告")) {
                String errorInfo = parts[0].trim();
                // 移除多余的提示信息
                errorInfo = errorInfo.replaceAll("代码中有语法错误,|以下是修改后的代码:", "");
                result.append("\n\n").append(errorInfo);
            }
        } else {
            result.append(aiResponse.trim());
        }
        
        return result.toString();
    }

    private double getCpuUsage() {
        com.sun.management.OperatingSystemMXBean osBean = 
            (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        return Math.round(osBean.getProcessCpuLoad() * 1000.0) / 10.0;
    }

    private long getMemoryUsage() {
        Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        return (totalMemory - freeMemory) / (1024 * 1024);
    }
}

5.安装Java SDK依赖

        <dependency>
            <groupId>cn.bigmodel.openapi</groupId>
            <artifactId>oapi-java-sdk</artifactId>
            <version>release-V4-2.3.0</version>
        </dependency>
<!--WebSocket依赖-->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.3.8</version>
        </dependency>

6.使用方法

  为了照顾到所有人,简单介绍一下怎样使用,在CloudEduAssistant类中点击鼠标右键”Run“即可

运行成功后如下图所示

这是我项目中调用到智谱API的部分,如果要展示在前端,大家自行修改,目前支持文本模型(GLM4-plus大模型),文生图(CogView,根据文字生成图片),文生视(CogVideoX,根据文本生成视频),代码模型调用(codegeex4,这个大家根据需要可以删除,因为我项目中有调用到代码模型),图像生成,视频生成均保留在本地磁盘,如果有homie完善出更好的方法,留下您宝贵的建议,我们互相探讨一下。

以上代码就是java调用智谱API的整个流程了,希望可以帮助到大家!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值