通过java接入 kimi 的sdk

## kimi 并没有提供java语言的sdk.有python和.net。我们通过curl 进行单次对话

首先在kimi后台创建api-key,查看可以使用的model

controller


        @GetMapping("/miki-msg")
    public void testChat() {
        // 调用默认示例请求
        String result = kimiService.sendChatRequest();
        System.out.println("API响应: " + result);

        // 或者使用通用方法发送自定义请求
        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> userMsg = new HashMap<>();
        userMsg.put("role", "user");
        userMsg.put("content", "什么是人工智能?");
        messages.add(userMsg);

        String customResult = kimiService.sendCustomChatRequest(
                "moonshot-v1-8k",
                messages,
                0.7
        );
        System.out.println("自定义请求响应: " + customResult);
    }

service

package com.example.usermanagement.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class KimiService {

    private final RestClient restClient;
    private final String apiKey;
    private final String apiUrl;

    // 从配置文件注入API密钥和URL
    public KimiService(
            @Value("${moonshot.api-key}") String apiKey,
            @Value("${moonshot.base-url:https://api.moonshot.cn/v1}") String baseUrl) {
        this.apiKey = apiKey;

        this.apiUrl = baseUrl + "/chat/completions";

        // 初始化RestClient
        this.restClient = RestClient.builder()
                .baseUrl(baseUrl)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .build();
    }

    /**
     * 调用Moonshot chat completions API
     */
    public String sendChatRequest() {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "kimi-k2-0711-preview");

            // 构建messages列表
            List<Map<String, String>> messages = new ArrayList<>();

            // 添加system消息
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。");
            messages.add(systemMessage);

            // 添加user消息
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", "你好,我叫李雷,1+1等于多少?");
            messages.add(userMessage);

            requestBody.put("messages", messages);
            requestBody.put("temperature", 0.6);

            // 发送POST请求
            ResponseEntity<String> response = restClient.post()
                    .uri("https://api.moonshot.cn/v1/chat/completions")
                    .body(requestBody)
                    .retrieve()
                    .toEntity(String.class);

            // 返回响应体
            return response.getBody();

        } catch (Exception e) {
            e.printStackTrace();
            return "请求失败: " + e.getMessage();
        }
    }

    /**
     * 通用方法:发送自定义对话请求
     */
    public String sendCustomChatRequest(String model, List<Map<String, String>> messages, double temperature) {
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            requestBody.put("messages", messages);
            requestBody.put("temperature", temperature);

            ResponseEntity<String> response = restClient.post()
                    .uri("https://api.moonshot.cn/v1/chat/completions")
                    .body(requestBody)
                    .retrieve()
                    .toEntity(String.class);

            return response.getBody();

        } catch (Exception e) {
            e.printStackTrace();
            return "请求失败: " + e.getMessage();
        }
    }
}

多次对话

Kimi API 与 Kimi 智能助手不同,API 本身不具有记忆功能,它是无状态的,这意味着,当你多次请求 API 时,Kimi 大模型并不知道你前一次请求的内容,也不会记忆任何请求的上下文信息。例如,你在前一次请求中告诉 Kimi 大模型你今年 27 岁,在下一次请求中,Kimi 大模型并不会记住你 27 岁这件事。

因此,我们需要手动维护每次请求的上下文,即 Context,把上一次请求过的内容手动加入到下一次请求中,让 Kimi 大模型能正确看到此前我们都聊了什么。我们将改造上一章节中使用的示例,来展示如何通过维护 messages 列表让 Kimi 大模型拥有记忆,并实现多轮对话功能。

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!