【个人学习||agent底层】01创建基础的发送和模型建立联系

创建基础的发送

agent的模型一般大都由服务商提供,而agent功能是让本机和服务商的模型建立联系,因此第一步是简单的建立联系

本文以deepseek为例
https://api-docs.deepseek.com/zh-cn/

也就是说我们发送的http应该和他要求的一样

Maven依赖

jackson

maven 复制代码
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.18.2</version>
</dependency>

代码编写

思路

java代码需要转为http,发给服务商,再把服务商返回的转回java代码

需要ObjectMapper mapper,实现java和json的转换

需要HttpClient httpClient,实现http的收发

deepseek为例,官方文档要求定义key,mode,url

java 复制代码
public class DPAgent {

    public static final String API_KEY = "sk-";
    public static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    public static final String MODEL = "deepseek-chat";

    //jackson的类,将java代码转为json和把jso解析为java
    private static final ObjectMapper mapper = new ObjectMapper();
    //http发送器
    private static final HttpClient httpClient = HttpClient.newHttpClient();
    //字符串构建
    static final StringBuilder stringBu = new StringBuilder();
}

定义主函数,用来接受终端的用户输入

java 复制代码
    public static void main(String[] args) throws Exception {
        while (true) {
            Scanner input = new Scanner(System.in);
            System.out.print("我: ");
            String Prompt = input.nextLine();
            DPAgent.chat(Prompt);
        }
    }
java 复制代码
    //发送函数
    public static void chat(String Prompt) throws Exception {
        String input = """
                用户问题:%s
                规则:对话形式回答简洁明了步捏找数据
                """.formatted(Prompt);

        //放入字符串构建器
        stringBu.append(input);

        //用Map创建http请求
        Map<String, Object> body = new HashMap<>();
        body.put("model", MODEL);
        body.put("messages",
                new Object[]{
                        Map.of(
                                "role", "user",
                                "content", stringBu.toString())
                }
        );
        body.put("temperature", 0.1);


        //用 ObjectMapper  把Map 转成json格式的字符串
        String json = mapper.writeValueAsString(body);

        //创建Http请求对象
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL))
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();

        // 用HttpClient 发送请求对象,并且得到响应对象
        HttpResponse<String> resp = httpClient.send(request,
                HttpResponse.BodyHandlers.ofString());

        //输出结果
        System.out.println(resp.body());

    }

总代码

java 复制代码
public class DPAgent {
    public static final String API_KEY = "sk-";
    public static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    public static final String MODEL = "deepseek-chat";

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final HttpClient httpClient = HttpClient.newHttpClient();
    static final StringBuilder stringBu = new StringBuilder();

    public static void main(String[] args) throws Exception {
        while (true) {
            Scanner input = new Scanner(System.in);
            System.out.print("我: ");
            String Prompt = input.nextLine();
            DPAgent.chat(Prompt);
        }
    }

    public static void chat(String Prompt) throws Exception {
        String input = """
                用户问题:%s
                规则:对话形式回答简洁明了步捏找数据
                """.formatted(Prompt);

        stringBu.append(input);

        //创建http请求
        Map<String, Object> body = new HashMap<>();
        body.put("model", MODEL);
        body.put("messages",
                new Object[]{
                        Map.of(
                                "role", "user",
                                "content", stringBu.toString())
                }
        );
        body.put("temperature", 0.1);
        //用 ObjectMapper  把Map 转成json格式的字符串
        String json = mapper.writeValueAsString(body);
        //创建Http请求对象(和文档匹配)
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL))
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();

        // 用HttpClient 发送请求对象,并且得到响应对象
        HttpResponse<String> resp = httpClient.send(request,
                HttpResponse.BodyHandlers.ofString());
        System.out.println(resp.body());

    }
}
    

最终结果

相关推荐
晓梦林11 小时前
BUUCTF findKey-学习笔记
笔记·学习
05664611 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
炎武丶航14 小时前
汽车功能测试学习(1):FCW前方碰撞预警
功能测试·学习·汽车
qq_1851986919 小时前
SpingBoot3入门学习一
学习
噗噗夹的TA之旅19 小时前
Shader 学习 21:自定义 Render Feature
学习·游戏·unity·c#·游戏引擎·图形渲染
码农小韩20 小时前
AIAgent应用开发——大模型理论基础与应用(七)
python·学习·ai·大模型·agent
流云鹤21 小时前
05Java学习day(5)
java·学习
only-lucky21 小时前
QML深入学习五(Controls模块)
前端·javascript·学习
Yolanda_20221 天前
Python学习-第九部分-错误处理与异常处理
开发语言·python·学习
一只小菜鸡..1 天前
南京大学 操作系统 (JYY) 学习笔记:CPU 的局限、GPU 与 AI 时代的算力革命
人工智能·笔记·学习