springboot调用大模型(二.调用ollama)

二.调用ollama

推荐理由:稳定,对linux操作系统友好,支持苹果,springai可以直接调用

缺点:无可视化操作界面,对多模态模型支持差(也有可能是我没研究透彻)

1.下载ollama

官网:https://ollama.com

2.安装

3.基础命令

ollama list:显示模型列表
ollama show:显示模型的信息
ollama pull:拉取模型
ollama push:推送模型
ollama cp:拷贝一个模型
ollama rm:删除一个模型
ollama run:运行一个模型

4.外部模型导入,(量化版模型,gguf

新建for_ollama.txt,文件(要与你下载的gguf在同一文件夹下)

内容

from ./xxxxxxx.gguf

命令行切换到文件夹下运行

ollama create '自定义模型名称' -f for_ollama.txt

5.调用(传统方法未使用springai,如需使用springai可参考官网:https://springdoc.cn/spring-ai/api/chat/ollama-chat.html)



import org.json.JSONArray;
import org.json.JSONObject;

import javax.imageio.*;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class OllamaVisionClientJDK8 {
    private final String baseUrl;

    public OllamaVisionClientJDK8() {
        this("http://localhost:11434");
    }

    public OllamaVisionClientJDK8(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String analyzeImage(List<String> imagePaths, String prompt) throws Exception {
        // 1. 编码图片
        JSONArray jSONArray =  new JSONArray();
        for (String imagePath : imagePaths) {
            String base64Image = convertTiffToBase64(imagePath, 0);
            jSONArray.put(base64Image);
        }




        JSONObject jsonObjectRequest = new JSONObject();
        jsonObjectRequest.put("model", "minicpm-v");//模型名称
        jsonObjectRequest.put("prompt", prompt); // 自动处理特殊字符
        jsonObjectRequest.put("images", jSONArray);
        jsonObjectRequest.put("stream", false);

        String jsonRequest =jsonObjectRequest.toString();

        // 3. 创建HTTP连接
        URL url = new URL(baseUrl + "/api/generate");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        // 4. 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonRequest.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        // 5. 检查响应
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
//            throw new RuntimeException("API请求失败: HTTP错误码 " + responseCode);
            throw new RuntimeException(connection.getResponseMessage());
        }

        // 6. 读取响应
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), "utf-8"))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }

            // 7. 提取响应内容
            return extractResponseContent(response.toString());
        }
    }

    private String extractResponseContent(String jsonResponse) {
        int start = jsonResponse.indexOf("\"response\":\"") + 12;
        if (start < 12) {
            throw new RuntimeException("无效的API响应: " + jsonResponse);
        }

        int end = jsonResponse.indexOf("\"", start);
        if (end <= start) {
            throw new RuntimeException("无效的API响应格式");
        }

        return jsonResponse.substring(start, end)
                .replace("\\n", "\n")
                .replace("\\\"", "\"")
                .replace("\\\\", "\\");
    }


    public static String convertTiffToBase64(String tifPath, int page) throws Exception {
        // 读取TIF(需JDK支持TIFF插件)
        BufferedImage tiffImage = ImageIO.read(new File(tifPath));

        // 多页处理(示例仅取第一页)
        // 实际需用 ImageReader 迭代页面

        // 转换为PNG
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(tiffImage, "png", baos);

        // Base64编码
        return Base64.getEncoder().encodeToString(baos.toByteArray());
    }






    public static void main(String[] args) {
        try {
            OllamaVisionClientJDK8 client = new OllamaVisionClientJDK8();
            List<String> list=new ArrayList<>();
            list.add("C:\\Users\\wwb\\Desktop\\img\\001.tif");
            // 示例用法
            String result = client.analyzeImage(
                    list
                    ,
                    "描述一下第一张图片"

            );

            System.out.println("=== 识别结果 ===");
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
rs\\wwb\\Desktop\\img\\001.tif");
            // 示例用法
            String result = client.analyzeImage(
                    list
                    ,
                    "描述一下第一张图片"

            );

            System.out.println("=== 识别结果 ===");
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Logo

这里是“一人公司”的成长家园。我们提供从产品曝光、技术变现到法律财税的全栈内容,并连接云服务、办公空间等稀缺资源,助你专注创造,无忧运营。

更多推荐