使用Spring Ai创建多个大语言模型的客户端(openrouter)

使用Spring Ai创建基于openr.

使用Spring Ai创建基于openrouter的多个模型客户端,config代码如下:

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class LlmModelConfig{


    @Bean("deepSeekChatClient")
    public ChatClient deepSeekChatClient() {
        OpenAiApi openAiApi = OpenAiApi.builder()
                .apiKey("sk-or-v1-asdfasf")
                .baseUrl("https://openrouter.ai/api")
                .build();

        OpenAiChatModel deepseekModel = OpenAiChatModel.builder()
                .openAiApi(openAiApi)
                .defaultOptions(OpenAiChatOptions.builder().model("deepseek/deepseek-chat-v3-0324:free").temperature(0.3).build())
                .build();

        return ChatClient.builder(deepseekModel).build();
    }

    @Bean("qwen3CoderChatClient")
    public ChatClient qwen3CoderChatClient() {
        OpenAiApi openAiApi = OpenAiApi.builder()
                .apiKey("sk-or-v1-xxxx")
                .baseUrl("https://openrouter.ai/api")
                .build();

        OpenAiChatModel deepseekModel = OpenAiChatModel.builder()
                .openAiApi(openAiApi)
                .defaultOptions(OpenAiChatOptions.builder().model("qwen/qwen3-coder:free").temperature(0.3).build())
                .build();

        return ChatClient.builder(deepseekModel).build();
    }
}

如何使用对应的大语言模型客户端,代码如下:


import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class JavaAiApplicationTests {

	@Qualifier("deepSeekChatClient")
	@Resource
	private ChatClient deepseekv3ChatClient;
	@Qualifier("qwen3CoderChatClient")
	@Resource
	private ChatClient qwen3CoderChatClient;


	@Test
	void testDeepSeekHello() {
		String content = deepseekv3ChatClient.prompt("hello").call().content();
		System.out.println(content);
	}

	@Test
	void testQwenCoderHello() {
		String content = qwen3CoderChatClient.prompt("hello").call().content();
		System.out.println(content);
	}

}

效果如下:

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注