大部分模型的接口都兼容 openai 的规范,所以只需要针对不兼容的模型进行适配即可
测试代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| public class ChatModelsMain {
private static final String BASE_URL = "https://api.deepseek.com/v1"; private static final String API_KEY = "api-key"; private static final String MODEL_NAME = "deepseek-chat";
public static void main(String[] args) {
if (!testConnection(BASE_URL, API_KEY, MODEL_NAME)) { System.out.println("模型配置未生效,请检查"); return; } System.out.println("模型配置已生效");
ChatModel chatModel = createModel(BASE_URL, API_KEY, MODEL_NAME);
System.out.println(chatModel.chat("你好"));
}
public static ChatModel createModel(String baseUrl, String apiKey, String modelName) { if (baseUrl == null || apiKey == null || modelName == null) { throw new IllegalArgumentException("模型配置信息不完整,请检查 baseUrl, apiKey 和 modelName"); }
if (modelName.equals("xxx")) { return null; }
return OpenAiChatModel.builder() .baseUrl(baseUrl) .apiKey(apiKey) .modelName(modelName) .build(); }
public static boolean testConnection(String baseUrl, String apiKey, String modelName) { try { ChatModel model = createModel(baseUrl, apiKey, modelName);
String response = model.chat("Say 'OK' in one word."); System.out.println("测试连接结果: " + response); return response != null && response.toLowerCase().contains("ok");
} catch (Exception e) { return false; } }
}
|
测试输出:
1 2 3 4 5
| 测试连接结果: OK 模型配置已生效 你好!很高兴见到你!😊 我是DeepSeek,由深度求索公司创造的AI助手。无论你有什么问题、需要什么帮助,或者只是想聊聊天,我都很乐意为你提供支持!
我可以帮你解答各种问题,协助处理文档,进行创作和分析等等。有什么我可以为你做的吗?我会尽我所能热情地帮助你!✨
|